为什么我必须在beforeEach()中调用spyOn? [英] Why do I have to call spyOn in a beforeEach()?
问题描述
我有一个简单的测试套件,里面有一个 it
函数。我想知道在我调用的函数中是否调用了某个函数,所以我有这样的函数:
I have a simple test suite that has one it
function inside of it. I want to see if a certain function is called within the function I'm calling, so I have something like this:
describe("doStuff", function () {
var foo = new Foo();
spyOn(foo, "doOtherStuff");
foo.doStuff(true);
it("should do stuff and other stuff", function() {
expect(foo.stuffDone).toBe(true);
expect(foo.doOtherStuff).toHaveBeenCalled();
});
});
然而,这给了我错误:期待间谍,但得到了功能。
However, this gives me the error: Expected a spy, but got Function.
看了一下之后,我看到所有的例子中都有 spyOn
beforeEach
。所以,我把测试改为:
After looking around some, I saw all examples had the spyOn
in a beforeEach
. So, I changed my test to:
describe("doStuff", function () {
var foo = new Foo();
beforeEach(function() {
spyOn(foo, "doOtherStuff");
foo.doStuff(true);
});
it("should do stuff and other stuff", function() {
expect(foo.stuffDone).toBe(true);
expect(foo.doOtherStuff).toHaveBeenCalled();
});
});
这是有效的。我对茉莉花很陌生,所以我可能只是遗漏了一些明显的东西,但我只是想知道为什么它必须在 beforeEach
中为 spyOn
工作。只需使用 beforeEach
就足够了,但我想更好地了解正在发生的事情。谢谢。
And this works. I'm pretty new to jasmine, so I may just be missing something obvious, but I just want to know why it has to be in a beforeEach
for the spyOn
to work. It's easy enough to just use the beforeEach
, but I want to understand better what is going on. Thanks.
推荐答案
这只是因为Jasmine在不同的闭包中运行Specs。 描述
和它
只调用添加到队列然后由Jasmine执行的寄存器回调。 Jasmine总是清理间谍......
That is simply because Jasmine runs the Specs in a different closure. The describe
and it
calls only register callbacks that are added to a queue and then executed by Jasmine later. And Jasmine always cleans up the spies ...
但你也可以将 spyOn
添加到 it
回调。
But you can also add the spyOn
to the it
callback.
这篇关于为什么我必须在beforeEach()中调用spyOn?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!