摩卡嘲笑导入变量

时间:2017-10-11 16:18:12

标签: javascript unit-testing mocking mocha

这是我的模块和我要测试的功能:

import aVariable from 'aModule'

export function afunction() {
  //do something with the imported aVariable 
  //calculates result
  return result
});

我想为我的摩卡单元测试模拟aVariable。

import {afunction} from 'aModule.js'

describe('Tests', () => {
  it('should return expected', () => {
    expect(afunction()).to.equal(expected);
  });

这可能吗?

更新:

使用babel-rewire-plugin my .babelrc:

{
  "env": {
    "dev": {
      "presets": ["es2015"]
    },
    "test": {
      "plugins": ["rewire"]
    }
  }
}

当我用:

运行我的测试时
meteor test --meteortesting:mocha

我收到此错误:

TypeError: _getServiceUrl(...).__Rewire__ is not a function

当我使用时:

BABEL_ENV=test meteor test --meteortesting:mocha

我得到:

While processing files with ecmascript (for target web.browser):
/node_modules/rewire/lib/rewire.js:19:15: Filename must be a string

3 个答案:

答案 0 :(得分:0)

如果安装了babel-plugin-reire节点模块,您可以在测试中执行以下操作:

describe('Tests', () => {
  it('should return expected', () => {
    afunction.__Rewire__( 'aVariable', 'myStubVariableValue' );
    expect(afunction()).to.equal(expected);
    afunction.__ResetDependency__( 'aVariable' );
});

答案 1 :(得分:0)

我最终可以使用https://github.com/testdouble/testdouble.js

来模拟这些ES6导入。

使用testDouble.replace()方法。

答案 2 :(得分:-1)

您应在摩卡咖啡运行脚本中添加--require babel