gpt4 book ai didi

javascript - 为什么这个 Jasmine spy 会出错?

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

我有一些代码:

var bar = function() { ... };
var foo = function() { bar(); };

还有一个 Jasmine 测试:

describe('foo', function() {
it('calls bar', function() {
spyOn(window, 'foo'); // this line causes an error
spyOn(window, 'bar');
foo();
expect(bar).toHaveBeenCalled();
});
});

注释行导致此错误:

预期的 spy 栏已被调用。

Jasmine 是否在监视 foo 以某种方式破坏了它的原生实现?如果我删除注释行,则测试通过。

最佳答案

此特定测试的目的是检查 foo() 的调用是否会导致 bar() 的调用。为了这个目的,那个......

it('calls bar', function() {
spyOn(window, 'bar');
foo();
expect(bar).toHaveBeenCalled();
});

... 就足够了。是的,您必须模拟 bar 函数,因此它不会执行它的工作,而只会报告它的调用。但是您绝不应该使用 spyOn 来模拟 foo - 您正在测试函数,而不是模拟!

如果出于某种原因,您应该观察它,请使用 andCallThrough spy 方法:

it('calls bar', function() {
spyOn(window, 'foo').andCallThrough();
spyOn(window, 'bar');
foo();
expect(bar).toHaveBeenCalled();
});

这样 mock 仍然会被创建(所以你可以使用它的一些方法——例如检查函数被调用了多少次);不同之处在于在模拟作业结束时调用原始函数 foo

关于javascript - 为什么这个 Jasmine spy 会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18925446/

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