【问题标题】:Mocha, Chai, Sinon test error in multiple filesMocha、Chai、Sinon测试多个文件出错
【发布时间】:2017-12-21 11:06:16
【问题描述】:

我有多个文件要测试,所有这些文件都使用相同的自定义 ../tools/http.util.js 库,如下所示:

const HttpUtil = require('../libs/http.util');

所以,我用这段代码在每个文件中模拟这个库:

before('before', function () {
    let HttpUtilMock = sinon.stub();
    HttpUtilMock.prototype.formGetUri = sinon.stub().returns("http://mock.com/");
    HttpUtilMock.prototype.formBaseRequestHeader = sinon.stub().returns("headers");
    testFunction.__set__("HttpUtil", HttpUtilMock);
});

当我运行mocha test/ --recursive --timeout=3000 时,我得到问题http.util 文件在第一个测试文件中被模拟,但它在第二个文件中没有被模拟 - 我从 @ 得到错误987654326@ 同时开始第二个文件测试。

我假设,我必须在完成第一个文件测试后清除测试数据,但我找不到任何用于 sinon 的清除命令,以清除变量 mock。

【问题讨论】:

  • testFunction.__set__ 来自哪里?
  • @bhoo-day 它是 rewire 模块的一部分 - 用于测试私有函数或设置私有变量的选项

标签: node.js unit-testing mocha.js sinon


【解决方案1】:

要清除 sinon 模拟,请使用恢复方法 myMock.restore();

【讨论】:

    【解决方案2】:

    我正在考虑的另一种替代方法是使用 rewire 模块。

    ....
    const sinon = require('sinon');
    let sandbox;
    
    before('before', function () {
        sandbox = sinon.sandbox.create();
        sandbox.stub(HttpUtil, 'formGetUri').returns('http://mock.com');
        sandbox.stub(HttpUtil, 'formBaseRequestHeader').returns('headers');    
    });
    
    after('after', function() {
      sandbox.restore();
    });
    

    测试完成后必须致电restore()

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 2015-12-01
      • 2018-04-08
      • 2018-11-05
      • 2017-10-23
      • 1970-01-01
      • 2017-11-21
      • 2017-03-25
      • 2023-03-22
      相关资源
      最近更新 更多