简体   繁体   English

Mocha,Chai和Sinon在多个文件中测试错误

[英]Mocha, Chai, Sinon test error in multiple files

I have multiple files to test, all these files are using the same custom ../tools/http.util.js library like this: 我有多个文件要测试,所有这些文件都使用相同的自定义../tools/http.util.js库,如下所示:

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

So, I'm mocking this library in each file with this code: 因此,我使用以下代码在每个文件中模拟该库:

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

When I run mocha test/ --recursive --timeout=3000 , I get the problem : http.util file is mocked in the first test file, but it is not mocking in the second file - I get errors from the http.util while starting the second file test. 当我运行mocha test/ --recursive --timeout=3000 ,出现问题 :第一个测试文件中http.util文件,但第二个文件中却没有http.util -我从http.util得到错误在开始第二个文件测试时。

I assume, that I have to clear test data after completing the first file tests, but I couldn't find any clear commands for sinon, to clear the variable mock. 我以为我必须在完成第一个文件测试后清除测试数据,但是我找不到用于sinon的任何清除命令来清除变量嘲笑。

要清除sinon模拟,请使用还原方法myMock.restore();。

Another alternative that I'm thinking of instead of using rewire module. 我正在考虑的另一种替代方法,而不是使用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();
});

must call restore() after tests finished. 测试完成后必须调用restore()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM