ember.jsember-clisinonember-cli-addons

How can I import sinon into an ember-cli test?


I'm trying to use sinon in my ember-cli app and I can't figure out how to import it. I have an import statement in the spec:

import { sinon } from 'sinon';

and then I try to use sinon in a test:

it('finds the todo model', function () {
  var store = this.subject().store;
  var spy = sinon.spy(store, 'find');

  this.subject().model();

  expect(spy).to.have.been.called;
});

however, when I run ember test from the command line I get this error:

not ok 8 PhantomJS 1.9 - TestLoader Failures my-app/tests/unit/routes/application-test: could not be loaded
---
    message: >
        Could not find module `sinon` imported from `my-app/tests/unit/routes/application-test`
    stack: >
        Error: Could not find module `sinon` imported from `my-app/tests/unit/routes/application-test`
            at requireFrom (http://localhost:7357/assets/vendor.js:119)
            at reify (http://localhost:7357/assets/vendor.js:106)
            at http://localhost:7357/assets/vendor.js:149
            at tryFinally (http://localhost:7357/assets/vendor.js:30)
            at http://localhost:7357/assets/vendor.js:156
            at http://localhost:7357/assets/test-loader.js:29
            at http://localhost:7357/assets/test-loader.js:21
            at http://localhost:7357/assets/test-loader.js:40
            at http://localhost:7357/assets/test-support.js:13918
    Log: >
...

The one thing I've noticed is that ember-sinon has a very light footprint in the bower_components/ directory:

$ls bower_components/sinon/
index.js

I've tried changing the import line to import { sinon } from 'sinon/index'; but that hasn't worked either.

Any help would be greatly appreciated. I'm very new to ember-cli, bower and es6 modules so links to background on those pieces would be greatly appreciated. Thanks!


Solution

  • OK, after RTFMing for litterally minutes, I found the answer right there in the test assets section of the ember-cli documentation.

    The setup:

    ember install ember-sinon
    

    ^ this will throw an error so I ran the generator by hand.

    ember generate ember-sinon
    

    Then, import sinon in the Brocfile:

    var isProduction = EmberApp.env() === 'production';
    if (!isProduction) {
      app.import(app.bowerDirectory + '/sinon/index.js', {type: 'test'});
    }
    

    Now, you can use sinon.stub/spy/mock in your specs but you'll still get a jshint error about sinon not being defined. I fixed this by adding:

    /* global sinon */
    

    to the top of the spec. It looks like you should be able to declare this globally in the jshintrc file but I haven't figured that out yet.