監視屬性
屬性比函數複雜。在 Jasmine 中,您可以使用屬性偵查員執行任何使用函數偵查員執行的操作,但您可能需要使用不同的語法。
使用 spyOnProperty
建立取用器偵查器或設定器偵查器。
it("allows you to create spies for either type", function() {
spyOnProperty(someObject, "myValue", "get").and.returnValue(30);
spyOnProperty(someObject, "myValue", "set").and.callThrough();
});
變更現有偵查器值比函數更困難,因為您無法在不呼叫其 getter
方式的情況下參考屬性。若要變通解決此問題,您可以儲存偵查器參考以供後續變更。
beforeEach(function() {
this.propertySpy = spyOnProperty(someObject, "myValue", "get").and.returnValue(1);
});
it("lets you change the spy strategy later", function() {
this.propertySpy.and.returnValue(3);
expect(someObject.myValue).toEqual(3);
});
如果儲存偵查器參考很奇怪,您也可以使用 Object.getOwnPropertyDescriptor
在測試中的任何位置存取它。
beforeEach(function() {
spyOnProperty(someObject, "myValue", "get").and.returnValue(1);
});
it("lets you change the spy strategy later", function() {
Object.getOwnPropertyDescriptor(someObject, "myValue").get.and.returnValue(3);
expect(someObject.myValue).toEqual(3);
});
您可以透過傳遞屬性陣列或雜湊作為 createSpyObj
的第三個參數,快速建立包含多個屬性的偵查器物件。這種情況下,您不會擁有建立的偵查器參考,因此如果您需要稍後變更其偵查器策略,則必須使用 Object.getOwnPropertyDescriptor
方法。
it("creates a spy object with properties", function() {
let obj = createSpyObj("myObject", {}, { x: 3, y: 4 });
expect(obj.x).toEqual(3);
Object.getOwnPropertyDescriptor(obj, "x").get.and.returnValue(7);
expect(obj.x).toEqual(7);
});