gpt4 book ai didi

javascript - 测试异步运行时如何使用 sinon 沙箱?

转载 作者:行者123 更新时间:2023-11-29 14:42:27 31 4
gpt4 key购买 nike

我有一些代码正在尝试使用这样的结构进行测试(根据 Cleaning up sinon stubs easily ):

function test1() {
// manually create and restore the sandbox
var sandbox;
beforeEach(function () {
sandbox = sinon.sandbox.create();
sandbox.stub(globalVar, "method", function() { return 1; });
});

afterEach(function () {
sandbox.restore();
});

it('tests something', function(done) {
anAsyncMethod(function() { doSomething(); done(); });
}
}

然后有一个类似的 test2() 函数。

但如果我这样做:

describe('two tests', function() {
test1();
test2();
}

我得到:

TypeError: Attempted to wrap method which is already wrapped

我做了一些日志记录以确定运行顺序,看来问题是它运行了 test1 beforeEach() Hook ,然后是 test2 beforeEach() 钩子(Hook),然后是 test1 it(),等等。因为它在到达 afterEach() 之前调用了第二个 beforeEach() > 从第一次测试开始,我们就遇到了问题。

有没有更好的方法来构建它?

最佳答案

您的测试规范的结构应如下所示:

describe("A spec (with setup and tear-down)", function() {
var sandbox;

beforeEach(function() {
sandbox = sinon.sandbox.create();
sandbox.stub(globalVar, "method", function() { return 1; });
});

afterEach(function() {
sandbox.restore();
});

it("should test1", function() {
...
});

it("should test2", function() {
...
});
});

或者你可以这样做:

function test1() {
...
}

function test2() {
...
}

describe("A spec (with setup and tear-down)", function() {
describe("test1", test1);
describe("test2", test2);
});

关于javascript - 测试异步运行时如何使用 sinon 沙箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36925936/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com