我们的测试是这样组织的:
describe("description", sinon.test(function() {
const harness = this;
it("should do something", function() {
// do something with harness.spy, harness.mock, harness.stub
});
}));当运行时,这些测试都在TypeError: harness.spy is not a function中失败。我添加了一些日志,发现在调用传递给it的函数之前,it存在并且是一个函数,但是在传递给it的函数中,harness.spy是undefined。
任何帮助,了解这里正在发生的事情,将不胜感激。
发布于 2016-12-14 01:59:55
问题在于Mocha执行代码的顺序。用describe包装回调到sinon.test无法工作。这是因为对所有describe的回调在it中的任何测试开始执行之前完成了执行。按照sinon.test的工作方式,它创建一个新的沙箱,使用沙箱的一些方法(spy、stub等)来检测this,然后调用它的回调,当回调返回时,sinon.test从this中移除它添加的方法。
因此,sinon.test包装describe回调所执行的任何设置都必须在运行任何测试之前取消。这里有一个例子,我在这里放了一些console.log。您将看到两个console.log语句在运行任何测试之前都会执行。
const sinon = require("sinon");
describe("description", sinon.test(function() {
const harness = this;
it("should do something", function() {
});
console.log("end of describe");
}));
console.log("outside");您需要将传递给it的回调包装起来,如下所示:
const sinon = require("sinon");
describe("description", function() {
it("should do something", sinon.test(function() {
this.spy();
}));
});
console.log("outside");如果sinon.test创建的沙箱的生存期对您无效,那么您必须创建沙箱并“手动”清除它,如下所示:
const sinon = require("sinon");
describe("description", function() {
let sandbox;
before(function () {
sandbox = sinon.sandbox.create();
});
after(function () {
sandbox.restore();
});
it("should do something", function() {
sandbox.spy();
});
it("should do something else", function() {
// This uses the same sandbox as the previous test.
sandbox.spy();
});
});https://stackoverflow.com/questions/41132663
复制相似问题