Sinon 存根未正确恢复

Sinon stubs are not restored properly

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

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

Attempted to wrap <method1> which is already wrapped

我就是这样做的

这是一个测试用例:

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

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

下一步应该知道上一步已经完成,需要调用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();
        });
});