如何用Jasmine窥探一个value属性(而不是一个方法) [英] How to spyOn a value property (rather than a method) with Jasmine
问题描述
Jasmine的 spyOn
可以改变方法的行为,但有没有办法改变对象的值属性(而不是方法)?代码如下所示:
Jasmine's spyOn
is good to change a method's behavior, but is there any way to change a value property (rather than a method) for an object? the code could be like below:
spyOn(myObj, 'valueA').andReturn(1);
expect(myObj.valueA).toBe(1);
推荐答案
2017年2月,他们合并了PR添加此功能,他们在2017年4月发布。
In February 2017, they merged a PR adding this feature, they released in April 2017.
所以要监视你使用的getter / setter:
const spy = spyOnProperty(myObj,' myGetterName','get');
其中myObj是您的实例,'myGetterName'是您在类中定义的名称 get myGetterName(){ }
,第三个参数是类型获取
或设置
。
so to spy on getters/setters you use:
const spy = spyOnProperty(myObj, 'myGetterName', 'get');
where myObj is your instance, 'myGetterName' is the name of that one defined in your class as get myGetterName() {}
and the third param is the type get
or set
.
您可以使用与已使用 spyOn
创建的间谍相同的断言。
You can use the same assertions that you already use with the spies created with spyOn
.
所以你可以举例如:
const spy = spyOnProperty(myObj, 'myGetterName', 'get'); // to stub and return nothing. Just spy and stub.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); // to stub and return 1 or any value as needed.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); // Call the real thing.
以下是github源代码中的行,如果您感兴趣,可以使用此方法。
Here's the line in the github source code where this method is available if you are interested.
用茉莉花回答原始问题2.6.1,你会:
Answering the original question, with jasmine 2.6.1, you would:
const spy = spyOnProperty(myObj, 'valueA', 'get').andReturn(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();
这篇关于如何用Jasmine窥探一个value属性(而不是一个方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!