【问题标题】:How can I import sinon into an ember-cli test?如何将 sinon 导入 ember-cli 测试?
【发布时间】:2015-05-04 20:29:17
【问题描述】:

我正在尝试在我的 ember-cli 应用程序中使用 sinon,但我不知道如何导入它。我在规范中有一个导入声明:

import { sinon } from 'sinon';

然后我尝试在测试中使用 sinon:

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;
});

但是,当我从命令行运行 ember test 时,我得到了这个错误:

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: >
...

我注意到的一件事是ember-sinonbower_components/ 目录中的占用空间非常小:

$ls bower_components/sinon/
index.js

我尝试将导入行更改为import { sinon } from 'sinon/index';,但这也没有奏效。

任何帮助将不胜感激。我对 ember-cli、bower 和 es6 模块非常陌生,因此非常感谢这些模块的背景链接。谢谢!

【问题讨论】:

    标签: ember.js ember-cli sinon ember-cli-addons


    【解决方案1】:

    好的,在 RTFMing 几分钟后,我在 ember-cli 文档的 test assets 部分找到了答案。

    设置:

    ember install ember-sinon
    

    ^ 这会引发错误,所以我手动运行了生成器。

    ember generate ember-sinon
    

    然后,在Brocfile中导入sinon:

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

    现在,您可以在规范中使用sinon.stub/spy/mock,但您仍然会收到关于未定义 sinon 的 jshint 错误。我通过添加来解决这个问题:

    /* global sinon */
    

    到规范的顶部。看起来您应该能够在 jshintrc 文件中全局声明它,但我还没有弄清楚。

    【讨论】:

    • 要摆脱 jshint 错误,您必须在“tests/.jshintrc”中的 predef 数组中添加“sinon”。不是项目范围的“.jshintrc”!!应该看起来像 { "predef": [ "sinon" ] };
    • 感谢@phlppn,这正是 jshint 的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2014-08-02
    • 2015-11-16
    相关资源
    最近更新 更多