Service injection fails in tests for ember-ajax


#1

So I recently migrated my code from using ember-cli-ic-ajax to using ember-ajax. However, I can no longer get my tests with mocked ajax calls to work anymore. The tests are reporting at the ajax service is undefined. Anyone have any ideas?

	
TypeError: Cannot read property 'request' of undefined
    at _favoriteRequest (frontend/pods/components/resource-favorite-button/component.js:60:24)
    at click (frontend/pods/components/resource-favorite-button/component.js:77:27)
    at Object.<anonymous> (http://localhost:7357/assets/tests.js:6958:15)
    at Object.wrapper (http://localhost:7357/assets/test-support.js:11689:29)
    at runTest (http://localhost:7357/assets/test-support.js:2750:28)
    at Object.Test.run (http://localhost:7357/assets/test-support.js:2735:4)
    at http://localhost:7357/assets/test-support.js:2877:11
    at process (http://localhost:7357/assets/test-support.js:2537:24)
    at begin (http://localhost:7357/assets/test-support.js:2519:2)
    at http://localhost:7357/assets/test-support.js:2579:4
  _favoriteRequest(resource, method) {
    return this.get('ajax').request(resource.get('links.favorite'), {
      method,
      dataType: 'json'
    });
  },
  ajax: Ember.inject.service(),
test('click | when resource.favorited == false', function(assert) {
  assert.expect(1);
  let favoriteUrl = 'http://path/to/favorite';
  let resource = Ember.Object.create({
    favorited: false,
    links: {
      favorite: favoriteUrl
    }
  });
  let session = {
    authorize() {
    }
  };
  let notify = {
    success() {
      assert.ok(true, 'notify.success was called');
    }
  };
  let component = this.subject({
    resource,
    session,
    notify
  });
  Ember.$.mockjax({
    type: 'PUT',
    url: favoriteUrl,
    status: 204,
    dataType: 'json',
    responseTime: 1,
    responseText: []
  });
  component.click();
});

#2

Is this a unit test? If so, services are not injected by default. You will have to use the needs api.


#3

Yep, it’s a unit test.


#4

Awesome, adding needs: [ ‘service:ajax’ ] did the trick. Thanks!