我有多个文件使用sinon对同一方法Utils.getTimestamp
进行存根处理。
运行测试文件时,一次通过所有测试。 一次运行测试文件时,测试失败,并出现以下错误:TypeError:“试图包装已经包装的getTimestamp”
在这两个文件中,我都有describe块以及一个before和after块
在Before块中,我对方法进行存根: getTimestampStub = sinon.stub(实用工具,'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();
});
});
答案 0 :(得分:1)
当Mocha运行多个文件时,它将首先运行所有之前的块。一个文件或多个文件都是如此。
然后的错误是因为我试图在恢复该方法之前对同一方法进行存根。像这样:
之前()
it()
before()//还没有恢复,调用了第二个sinon.stub吗? “试图包裹…… 已经包装好了”
it()
after()//解开
after()//已经恢复,另一个错误:“恢复不是函数”
然后的解决方案是在我需要的Assertion块中创建存根。像这样的东西:
文件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(() => {});
});
答案 1 :(得分:0)
您可以使用beforeEach()
和afterEach()
替换before()
和after()
,而不必移动存根并将调用恢复到每个单独的it()
块中。
What is the difference between `before()` and `beforeEach()`?