node.js - Sinon错误尝试包装已经包装的函数

标签 node.js sinon

虽然这里有同样的问题,但我找不到我的问题的答案,所以我的问题是:

我正在使用 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/

相关文章:

javascript - Mongoose 问题: schema not defined

windows - Yeoman 命令无法在 Windows 7 中运行

javascript - 如何使用 sinon stub /模拟 Nodejs 需求的子模块

node.js - 使用 Jest 和 Sinon 测试具有属性的函数

javascript - 如何 stub 未直接传递给调用函数的函数?

javascript - 围绕 Bing 翻译和 Node.js 构建项目

javascript - 从 Node.JS 向 DocuSign 发送请求时强制设置 TLS 版本 1.2

node.js - NodeJS SSL 从哪里获取 .key 文件

node.js - Sinon 没有对 module.exports stub

函数调用时Javascript模拟第三方 Node 库