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

我正在使用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
  });
}

当我try 运行这个测试时,它会给我错误

Attempted to wrap getObj which is already wrapped

我也试着把

beforeEach(function () {
  sandbox = sinon.sandbox.create();
});

afterEach(function () {
  sandbox.restore();
});

在每一次描述中,都给了我同样的错误.

推荐答案

您应该恢复getObj in after()功能,请按以下方式try .

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()个存根模拟,并恢复sandbox.restore()个之前创建的所有假货,Arjun Malik给出了良好的example

Node.js相关问答推荐

在Nest.Js中,如何发送带有表单数据的正文请求并应用正文请求验证.附加的文件是可选的

填充函数在Node.js和MongoDB中不起作用

Node-Red Tasmota 错误:连接 ECONNREFUSED 192.168.77.21:1883

在 NodeJS 中使用 post 时出现错误 500TypeError: 无法解构 'req.body' 的属性 'name',因为它未定义

将 POST 的 json 变量格式化为 lambda

尽管 tsconfig 中提供了正确的路径,但仍出现找不到模块错误

PEAN auth 应用程序:为什么 Angular 拦截器总是使用BehaviorSubject 返回 null(即初始值),而不是更新后的值?

dayjs的isSameOrAfter方法未按预期工作

如何使用 $PATH 变量在系统中全局自动安装 bash 脚本?或者重写脚本到node

如何修改这个flake.nix,这样我就不用每次加载环境都加载nix包了

MERN 堆栈项目中的 React [create-react-app] 正在提供依赖项

如何在拦截器中发送不同的请求?

在 PassportJS 中使用多种本地策略

Webpack TypeScript module.hot 不存在

如何在 MongoDB 上只收听 localhost

Puppeteer 记录在 page.evaluate

NodeJS 中的 HTTPS 请求

`return function *(){...}` 是什么意思?

webpack-dev-server 找不到模块webpack

node.js 中的意外保留字导入