【问题标题】:mocha mocking imported variablemocha 模拟导入的变量
【发布时间】:2017-10-11 16:18:12
【问题描述】:

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

import aVariable from 'aModule'

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

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

import {afunction} from 'aModule.js'

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

这可能吗?

更新:

使用 babel-rewire-plugin 我的 .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

【问题讨论】:

  • 你见过 babel 的 rewire 插件吗?它使您可以轻松地做这些事情。如果您不使用 babel,也可以使用 another rewire library
  • 我见过 rewire 但我不知道你可以用 i 模拟导入,我使用 Babel 作为转译器。

标签: javascript unit-testing mocking mocha.js


【解决方案1】:

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

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

【讨论】:

  • 会尽快试用
  • 我试过了,但在访问 x.__Rewire__ 时遇到了未定义的错误。我需要一些进口吗?
  • @Gobliins 你安装了babel rewire plugin 吗?
  • 尝试将此添加到您的 .babelrc 文件中"env": { "test": { "plugins": ["rewire"] } }
  • 我仍然收到TypeError: aFunction(...).__Rewire__ is not a function ,我已经发布了我的`.babelrc`,请参阅我的问题中的更新
【解决方案2】:

我终于可以使用 https://github.com/testdouble/testdouble.js 模拟这些 ES6 导入

使用testDouble.replace() 方法。

【讨论】:

    【解决方案3】:

    你应该在你的 mocha 运行脚本中添加 --require babel

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-26
      • 2020-10-09
      • 2018-11-21
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      相关资源
      最近更新 更多