預設間諜策略
Jasmine 建立間諜時,您可以自訂其使用的預設間諜策略。在正常情況下,預設策略為 .and.stub()
,若呼叫間諜則傳回 undefined
。若要變更這項設定,請於 beforeEach()
或 beforeAll()
區塊中使用 jasmine.setDefaultSpyStrategy
輔助函數。
beforeEach(function() {
jasmine.setDefaultSpyStrategy(and => and.returnValue("Hello World"));
});
it("returns the value Hello World", function() {
const spy = jasmine.createSpy();
expect(spy()).toEqual("Hello World");
});
呼叫 jasmine.setDefaultSpyStrategy
時不帶任何參數以移除自訂預設。在您想要暫時建立一連串間諜間諜策略時,這很有幫助。
it("throws if you call any methods", function() {
jasmine.setDefaultSpyStrategy(and => and.throwError(new Error("Do Not Call Me")));
const program = jasmine.createSpyObj(["start", "stop", "examine"]);
jasmine.setDefaultSpyStrategy();
expect(() => {
program.start();
}).toThrowError("Do Not Call Me");
});