ember.jsmocha.jstestem

How can I set up mocha tests to run Ember initializers so injected objects are defined?


My Ember app injects an "i18n" object into the container via an initializer, which is later looked up with "this.container.lookup('i18n:main')" in a controller 'preferredLanguage' computed property.

A mocha unit test which tests the controller 'preferredLanguage' property, fails due to "i18n is not defined". How can I set up the mocha tests to run Ember application initializers so injected objects are defined when looked up from the container during unit testing?


Solution

  • I've found that the main issue is (as you mentioned) is that the start-app.js file doesn't run when mocha is installed. I battled this for a while as well but have finally refined the process to get Ember and Mocha to play nicely. First you have to get ember-cli-mocha and ember-mocha setup correctly. Then you can explicitly import and invoke the startApp function in your tests/test-helper.js file to have Ember run and inject test helpers like it normally does with qunit. Here is what has worked for me with ember-cli 1.13.1.

    bower install ember-mocha
    bower install ember-test-helpers
    npm install ember-cli-mocha
    ember install ember-cli-mocha (say Y to overwrite test-helper.js)
    

    Then in tests/test-helper.js

    // tests/test-helper.js
    import resolver from './helpers/resolver';
    import { setResolver } from 'ember-mocha';
    
    // startApp doesn't run with mocha... so we run it explicitly
    import startApp from "./helpers/start-app";
    startApp();
    
    setResolver(resolver);
    

    After that you can create generate a route or controller and ember-cli-mocha will create test and you should have access to helpers like visit() and currentURL(); Though I found you need to actually setup the route and controller for those to work correctly.

    it("should have use of ember's test helpers", function() {
      visit("/mocha-test");
      andThen(function() {
        var url = currentURL();
        expect(url).to.equal("/mocha-test");
      });
    });