myartsev
myartsev

Reputation: 1232

Mock a service in an acceptance test with Ember 2.7.0

For older versions of ember, this is the accepted answer for mocking a service in an acceptance test

With Ember 2.7.0, I am not able to call startApp as per the answer above. However, upon some quick tests, this appears to work just fine in injecting a service.

import Ember from 'ember';
import { module, test } from 'qunit';

let speakerMock = Ember.Service.extend({
  speak: function() {
    console.log("Acceptance Mock!");
  }
});

module('Acceptance | acceptance demo', {
  beforeEach: function() {
    // the key here is that the registered service:name IS NOT the same as the real service you're trying to mock
    // if you inject it as the same service:name, then the real one will take precedence and be loaded
    this.application.register('service:mockSpeaker', speakerMock);

    // this should look like your non-test injection, but with the service:name being that of the mock.
    // this will make speakerService use your mock
    this.application.inject('controller', 'speakerService', 'service:mockSpeaker');
  }
});

test('visit a route that will trigger usage of the mock service' , function(assert) {
  visit('/');

  andThen(function() {
    assert.equal(currentURL(), '/');
  });
});

Am I missing something? I have doubts about:

a) Why this is not documented? Embers docs provide excellent documentation on stubbing services in components.

b) Is it because it is discouraged to mock services inside an acceptance test? Why?

Upvotes: 3

Views: 631

Answers (1)

ykaragol
ykaragol

Reputation: 6221

From the guide:

Acceptance tests are used to test user interaction and application flow. The tests interact with the application in the same ways that a user would, by doing things like filling out form fields and clicking buttons. Acceptance tests ensure that the features within a project are basically functional, and are valuable in ensuring the core features of a project have not regressed, and that the project's goals are being met.

It is not "clearly" mentioned but I understood that "acceptance tests behave the same with the real application". So you shouldn't mock something.

Upvotes: 0

Related Questions