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

how do I use sinon sandboxes when tests run asynchronously?

我有一些代码正在尝试使用这样的结构进行测试(根据 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() 挂钩,然后是 test2 beforeEach() 钩子,然后是 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);
});