简体   繁体   中英

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:

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.

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模拟,请使用还原方法myMock.restore();。

Another alternative that I'm thinking of instead of using rewire module.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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