【问题标题】:Sinon stubs are not restored properlySinon 存根未正确恢复
【发布时间】:2019-11-06 06:42:14
【问题描述】:

我正在使用 mocha、chai 和 sinon 来测试我的 node-express 代码。

我遇到了一个奇怪的问题,看起来 sinon 无法恢复存根,所以在下一次测试中我得到了已知错误

Attempted to wrap <method1> which is already wrapped

这就是我的工作

  • 我在测试用例中使用mocha-steps 而不是it() 子句,所以 它们按顺序运行(我想确保它不是异步的 比赛条件)
    • 我使用 sinon-test 自动清理存根,以防万一我做错了什么

这是一个测试用例:

step('should do stuff', test(function () {

    const stub1 = sinon.stub(my_model1, 'method1');

    chai.request(server)
        .get('/endpoint')
        .send(body)
        .end(function (err, res) {
            stub1.restore();
            do_various_assertions(err, res);
        });
}));

还有一个

step('should do other stuff', test(function () {

        const stub1 = sinon.stub(my_model1, 'method1');

        chai.request(server)
            .get('/endpoint')
            .send(slightly_different_body)
            .end(function (err, res) {
                stub1.restore();
                do_various_assertions(err, res);
            });
    }));

我在哪里得到上面的错误

Attempted to wrap <method1> which is already wrapped

如果我在第二种情况下注释掉存根工作正常。但为什么?我做错了什么?

【问题讨论】:

    标签: node.js mocha.js sinon


    【解决方案1】:

    下一步应该知道上一步已经完成,需要调用done函数。在您的示例中,第二步不等待第一步,method1 未恢复。

    step('should do stuff', function (done) {
    
        const stub1 = sinon.stub(my_model1, 'method1');
    
        chai.request(server)
            .get('/endpoint')
            .send(body)
            .end(function (err, res) {
                stub1.restore();
                do_various_assertions(err, res);
                done();
            });
    });
    

    【讨论】:

      猜你喜欢
      • 2016-09-21
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 2016-09-30
      • 2015-11-28
      • 1970-01-01
      • 2021-07-26
      • 2017-09-30
      相关资源
      最近更新 更多