Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当测试异步运行时,如何使用sinon沙盒?_Javascript_Testing_Mocha.js_Sinon_Stub - Fatal编程技术网

Javascript 当测试异步运行时,如何使用sinon沙盒?

Javascript 当测试异步运行时,如何使用sinon沙盒?,javascript,testing,mocha.js,sinon,stub,Javascript,Testing,Mocha.js,Sinon,Stub,我有一些代码正试图用这样的结构进行测试(per): 然后还有一个类似的test2()函数 但如果我这样做: describe('two tests', function() { test1(); test2(); } 我得到: TypeError: Attempted to wrap method which is already wrapped 我做了一些日志记录来确定运行顺序,问题似乎是它运行test1beforeach()hook,然后是test2beforeach()

我有一些代码正试图用这样的结构进行测试(per):

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

但如果我这样做:

describe('two tests', function() {
    test1();
    test2();
}
我得到:

TypeError: Attempted to wrap method which is already wrapped
我做了一些日志记录来确定运行顺序,问题似乎是它运行test1
beforeach()
hook,然后是test2
beforeach()
hook,然后是test1
it()
,等等,因为它在到达
afterEach()之前调用第二个
beforeach()
在第一次测试中,我们遇到了一个问题


我有没有更好的方法来组织这件事

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

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);
});

但是我希望能够将这两个规范放在函数中,这样我就可以在各种测试中重用它们。我希望它们是自包含的,这样我就不必每次调用它们时都创建沙盒和存根代码。那不可能吗?我明白你的意思。让我更新我的答案——对注释中的格式化代码仍然是陌生的。额外的descripe包装器——无论是在您拥有的时候,还是在每个测试函数中——都可以做到这一点。额外的报告层次,但尽可能做到最好。谢谢
function test1() {
  ...
}

function test2() {
  ...
}

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