【问题标题】:Sinon Error "Attempted to wrap ... which is already wrapped" on Multiple Files多个文件上的Sinon错误“尝试包装......已经包装”
【发布时间】:2019-09-22 02:12:19
【问题描述】:

我有多个文件使用 sinon 来存根相同的方法 Utils.getTimestamp

运行测试文件时,一次一个,所有测试都通过。 一次运行测试文件时,测试失败:TypeError: "Attempted to wrap getTimestamp which has been packed"

在这两个文件中,我都有带有前后块的描述块

在 Before 块中,我将以下方法存根: getTimestampStub= sinon.stub(Utils, 'getTimestamp') .returns(myTimestamp);

在 After 块中,我恢复了如下方法: getTimestampStub.restore();

我根据这个答案尝试了这个: https://stackoverflow.com/a/36075457/6584537

示例文件:

文件 1

describe("First Stub", () => {
    let getTimestampStub;
    before(() => {
        getTimestampStub= sinon.stub(Utils, 'getTimestamp') .returns("SOME_TIMESTAMP");
    });

    it("Should run some code that uses getTimestamp", () => {
        // Some code that in the process uses `Utils.getTimestamp`
    });
    after(() => {
        getTimestampStub.restore();
    });
});

文件 2

describe("Second Stub", () => {
    let getTimestampStub;
    before(() => {
        getTimestampStub= sinon.stub(Utils, 'getTimestamp') .returns("SOME_TIMESTAMP");
    });

    it("Should run some OTHER code that uses getTimestamp", () => {
        // Some code that in the process uses `Utils.getTimestamp`
    });

    after(() => {
        getTimestampStub.restore();
    });
});

【问题讨论】:

    标签: unit-testing mocking mocha.js sinon stub


    【解决方案1】:

    当 Mocha 运行多个文件时,它首先运行 所有之前的块。这适用于 1 个文件或多个文件。

    这个错误是因为我试图在它有机会恢复之前存根相同的方法。像这样的:

    之前()

    它()

    before() // 还没有恢复,第二个 sinon.stub 被调用了吗? “试图包装...... 已经包装好了”

    它()

    after() // 展开

    after() // 已经恢复,另一个错误:“Restore is not a function”

    然后解决方案是在我需要的断言块中创建存根。像这样:

    文件 1

    describe("First Stub", () => {
        let getTimestampStub;
        before(() => {});
    
        it("Should Stub getTimestamp before some code needs it", () => {
            getTimestampStub= sinon.stub(Utils, 'getTimestamp') .returns("SOME_TIMESTAMP");
    
            // Some code that in the process uses `Utils.getTimestamp`
    
            getTimestampStub.restore();
        });
        after(() => {});
    });
    

    文件 2

    describe("Second Stub", () => {
        let getTimestampStub;
        before(() => {});
    
        it("Should Stub getTimestamp before some code needs it", () => {
            getTimestampStub= sinon.stub(Utils, 'getTimestamp') .returns("SOME_TIMESTAMP");
    
            // Some code that in the process uses `Utils.getTimestamp`
    
            getTimestampStub.restore();
        });
        after(() => {});
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用beforeEach()afterEach() 替换before()after(),而不是将存根和恢复调用移动到每个单独的it() 块中。

      What is the difference between `before()` and `beforeEach()`?

      【讨论】:

        猜你喜欢
        • 2016-07-04
        • 2012-02-08
        • 1970-01-01
        • 1970-01-01
        • 2015-07-13
        • 2013-06-21
        • 1970-01-01
        • 1970-01-01
        • 2023-01-13
        相关资源
        最近更新 更多