虽然这里有同样的问题,但我找不到我的问题的答案,所以我的问题是:
我正在使用 mocha 和 chai 测试我的 Node js 应用程序。我正在使用 sinion 来包装我的函数。
describe('App Functions', function(){
let mockObj = sinon.stub(testApp, 'getObj', (dbUrl) => {
//some stuff
});
it('get results',function(done) {
testApp.someFun
});
}
describe('App Errors', function(){
let mockObj = sinon.stub(testApp, 'getObj', (dbUrl) => {
//some stuff
});
it('throws errors',function(done) {
testApp.someFun
});
}
当我尝试运行这个测试时,它给了我错误
Attempted to wrap getObj which is already wrapped
我也试过放
beforeEach(function () {
sandbox = sinon.sandbox.create();
});
afterEach(function () {
sandbox.restore();
});
在每个描述中,但仍然给我同样的错误。
最佳答案
你应该恢复after()
函数中的getObj
,请尝试如下。
describe('App Functions', function(){
var mockObj;
before(function () {
mockObj = sinon.stub(testApp, 'getObj', () => {
console.log('this is sinon test 1111');
});
});
after(function () {
testApp.getObj.restore(); // Unwraps the spy
});
it('get results',function(done) {
testApp.getObj();
});
});
describe('App Errors', function(){
var mockObj;
before(function () {
mockObj = sinon.stub(testApp, 'getObj', () => {
console.log('this is sinon test 1111');
});
});
after( function () {
testApp.getObj.restore(); // Unwraps the spy
});
it('throws errors',function(done) {
testApp.getObj();
});
});
2022/01/22 更新
使用 sinon's sanbox您可以使用 sandbox.stub()
创建 stub mocks 并恢复通过 sandbox.restore()
创建的所有假货,Arjun Malik 给出了一个很好的 example
关于node.js - Sinon错误尝试包装已经包装的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074631/