[英]How can I spy on a function and return a mock value from inside another function using jasmine?
[英]How can I spy on a getter property using jasmine?
我如何使用茉莉花來監視getter屬性?
var o = { get foo() {}, };
spyOn(o, 'foo').and.returnValue('bar'); // Doesn't work.
這也不起作用AFAICT:
spyOn(Object.getOwnPropertyDescriptor(o, 'foo'), 'get').and.returnValue('bar');
從Jasmine 2.6開始, spyOnProperty
就可以實現這spyOnProperty
。 要監視foo
屬性的訪問器,請執行以下操作:
spyOnProperty(o, 'foo')
這允許您使用間諜函數替換訪問器屬性的set
和/或get
訪問器函數。 您可以指定或set
或get
只作為第三個參數:
spyOnProperty(o, 'foo', 'get')
2017年2月,他們合並了PR添加此功能,他們於2017年4月發布。
所以要監視你使用的getter / setter: const spy = spyOnProperty(myObj, 'myGetterName', 'get');
其中myObj是你的實例,'myGetterName'是你的類中定義為get myGetterName() {}
,第三個param是get
或set
類型。
您可以使用已經與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源代碼中的行,如果您感興趣,可以使用此方法。
用jasmine 2.6.1回答原來的問題,你會:
var o = { get foo() {} };
spyOnProperty(o, 'foo', 'get').and.returnValue('bar');
我從@apsillers響應中獲取靈感並編寫了以下幫助器(要求prop可以如上所述進行配置)
let activeSpies = [];
let handlerInstalled = false;
function afterHandler() {
activeSpies.forEach(({ obj, prop, descriptor }) => Object.defineProperty(obj, prop, descriptor));
activeSpies = [];
}
export function spyOnGetter(obj, prop) {
const env = jasmine.getEnv();
const descriptor = Object.getOwnPropertyDescriptor(obj, prop);
const spy = jasmine.createSpy(`${prop} spy`);
const copy = Object.assign({}, descriptor, { get: spy });
Object.defineProperty(obj, prop, copy);
activeSpies.push({
obj,
prop,
descriptor,
});
if (!handlerInstalled) {
handlerInstalled = true;
env.afterEach(() => afterHandler());
}
return spy;
}
它可以像這樣使用:
import { spyOnGetter } from spyExtra;
it('tests the thing', () => {
spyOnGetter(myObj, 'myProp').and.returnValue(42);
expect(myObj.myProp).toBe(42);
});
希望它有用!
我認為最好的方法是使用spyOnProperty
。 它需要3個屬性,您需要傳遞get
或set
作為第三個屬性。
spyOnProperty(o, 'foo', 'get').and.returnValue('bar');
如果您無法使用最新的茉莉花(2.6.1),您可以這樣做
const getSpy = jasmine.createSpy().and.returnValue('bar')
Object.defineProperty(o, 'foo', { get: getSpy });
這里是defineProperty的文檔
我不相信你可以窺探吸氣劑。 getter的意思是它的行為與屬性完全相同,所以當jasmine從未像函數一樣被調用而是像屬性一樣被訪問時,它將如何能夠窺探它。
作為一種解決方法,你可以讓你的getter調用另一個函數並監視它。
var o = {
_foo: function(){
return 'foo';
},
get foo(){
return this._foo();
}
};
spyOn(o, '_foo').and.returnValue('bar');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.