Testing app initializers with ember-cli


#1

I have set up some initializers in my app and would like to do some tests on them. The simple case at this point is that my initializer hits the server to load a record and defers until the record has loaded. Once loaded it is then injected into the application controller and used accordinly.

What I want to do is navigate to /foo then mimic a page refresh (F5) and ensure that the object is indeed available on the controller. How do I mimic the F5 of the user in the test framework? Simply visiting the route after the app has started won’t do it for me. I’ve tried using App.reset(), but haven’t been able to get it to reload reload properly.

test('Refresh results keeps gravatar', function() {
  expect(4);
  visit('/results');
  andThen(function() {
    equal(currentURL(), '/results');
    // user hits refresh
    App.reset();
  });
  andThen(function() {
    // at this point the app doesn't show any route (currentURL() is "")
    equal(currentURL(), '/results');
    ok(find('.spec-header-gravatar img').length, 1);
  });
});

#2

I managed to figure it out. The App.reset() needs to be put into a run loop, then one needs to manually visit the route. It doesn’t remember it from before the reset.

...
andThen(function() {
    equal(currentURL(), '/results');
    // user hits refresh
    Em.run(function() {    
        App.reset();
    });
    visit('/results');
});
...

#3

I have a feeling that resetting the app could disrupt the ember test helpers that are in effect, but if this test is working for you maybe it’s ok.


#4

Try not to use use XHR stuff in initalizers, that’s for setting things up.


#5

I need to load a record from the server and populate it to the app controller before any route is initialized. Putting it in the beforeModel for the applicationController doesn’t work since if you navigate to foo its route doesn’t wait for the promises of the applicationRoute to resolve. Do you have a suggestion as to where else I should load the record?


#6

This issue that explains it more throughly. https://github.com/emberjs/ember.js/issues/4280#issuecomment-48088291

I think a cleaner solutions is to make an auth mixin, and include it in the routes that need it.


#7

Thanks for the link. I used to actually override the beforeModel in each route, but it seemed a bit tedious to me. Especially since I had to have some custom logic in my login/logout route. Now I can put everything into my initializers at the cost of one ajax call. Thanks for your input.