gpt4 book ai didi

testing - Jasmine spy 示例如何工作

转载 作者:行者123 更新时间:2023-11-28 20:03:54 24 4
gpt4 key购买 nike

全部;

我刚开始学习 Jasmine(2.0.3 版),当我进入 Spies 部分时,第一个示例让我感到困惑:

describe("A spy", function() {
var foo, bar = null;

beforeEach(function() {
foo = {
setBar: function(value) {
bar = value;
}
};

spyOn(foo, 'setBar');

foo.setBar(123);
foo.setBar(456, 'another param');
});

it("tracks that the spy was called", function() {
expect(foo.setBar).toHaveBeenCalled();
});

it("tracks all the arguments of its calls", function() {
expect(foo.setBar).toHaveBeenCalledWith(123);
expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
});

it("stops all execution on a function", function() {
expect(bar).toBeNull();
});
});

我想知道是否有人可以解释为什么 setBar 函数不影响 describe block 中定义的栏?Jasmine spy 如何处理这个问题?

谢谢

最佳答案

因为您实际上并没有执行这些方法。

如果你想让这个测试失败:

it("stops all execution on a function", function() {
expect(bar).toBeNull();
});

在这些调用之后:

foo.setBar(123);
foo.setBar(456, 'another param');

然后你应该为你的 spy 调用and.callThrough

spyOn(foo, 'setBar').and.callThrough();

来自 documentation

Spies: and.callThrough

By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation.

关于您的问题,“jasmine 如何处理这个问题?”

here你可以读到一个基本的解释:

Mocks work by implementing the proxy pattern. When you create a mock object, it creates a proxy object that takes the place of the real object. We can then define what methods are called and their returned values from within our test method. Mocks can then be utilized to retrieve run-time statistics on the spied function such as:

How many times the spied function was called.
What was the value that the function returned to the caller.
How many parameters the function was called with.

如果你想要所有的实现细节,你可以查看 Open Source 的 Jasmine 源代码 :)

在这个源文件 CallTracker 中,您可以看到如何收集有关方法调用的数据。

关于 the proxy pattern 的更多信息。

关于testing - Jasmine spy 示例如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512876/

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