Sinon存根未正确还原

问题描述 投票:0回答:1

我正在使用摩卡,柴和锡农来测试我的节点表达代码。

我遇到了一个奇怪的问题,看起来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 sinon
1个回答
0
投票

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

step('should do stuff', test(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();
        });
}));
© www.soinside.com 2019 - 2024. All rights reserved.