Search code examples
ember.jsember-cliecmascript-6

Ember-CLI tests can't include modules from 'app' directory


I am trying to include a module in my app from one of the tests. Is it even possible to do that? I am only able to include a module in the 'tests' directory. I keep getting the infamous "Could not find module" error.

http://localhost:4200/assets/test-support.js:5578:16: Could not find module d3graph/app/controllers/index imported from d3graph/tests/unit/utils/graph-helper-test

This is my test code:

import { moduleFor, test }  from 'ember-qunit';
import Ember from 'ember';
import helper from '../../../app/anything/anywhere';  // <- THIS LINE FAILS

moduleFor('util:graph-helper', 'Graph Helper', {
  beforeEach: () => initialize()
});

function initialize() { /* something */ };

test('test desc', function(assert) {
  var testObj = this.subject();

  // test logic follows
});

I did try various modifications of the path to the module, including absolute path from root, I even tried including via 'require()', but alas without success. Please help.


Solution

  • Shouldn't be a problem. You will need a needs line inside your moduleFor call:

    import { moduleFor, test }  from 'ember-qunit';
    import Ember from 'ember';
    
    moduleFor('util:graph-helper', 'Graph Helper', {
        needs: ['controller:index'],
    
       beforeEach: () => initialize()
    });
    
    function initialize() { /* something */ };
    
    test('test desc', function(assert) {
        var testObj = this.subject();
    
        // test logic follows
    });
    

    See http://guides.emberjs.com/v1.10.0/testing/testing-controllers/#toc_testing-controller-needs for more details about needs.

    Edit

    Disregard the above information... that's for Ember modules which resolve the standard way. To include modules off the beaten Ember path, a simple ES6 import will suffice (this example demonstrates pulling in some-util for the controller:index unit tests):

    import { moduleFor, test }  from 'ember-qunit';
    import Ember from 'ember';
    import SomeUsefulUtil from '<application-name>/utils/some-useful-util';
    
    moduleFor('controller:index', 'Graph Helper', {
       beforeEach: () => initialize()
    });
    
    function initialize() { /* something */ };
    
    test('test desc', function(assert) {
        var testObj = this.subject();
    
        // Create utility class instance
        var someUsefulUtilInstance = new SomeUsefulUtil();
    
        // test logic follows
    });
    

    The potentially non-intuitive part of this is that you have to prefix the import with your application's name instead of the standard app directory.