2

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?

bobvan
  • 251
  • 3
  • 9

1 Answers1

2

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");
  });
});
aricallen
  • 46
  • 4
  • OK I accept your answer. In may case, the 'assets js' files referenced by 'index' just aren't there so it just won't work. I get error 'Could not find module ember-cli/test-loader'. After 2 months, idle, I have a plethora of new errors and instructions to run bower install this or that, or this or that is deprecated or is undefined. I believe the Ember initiative has run its course at my company. I was the only advocate. When we resume development of the project based on Ember, it will be re-written on AngularJS. – bobvan Jul 24 '15 at 15:25