jasmine.createSpy
可以在沒有監視功能時使用。它會跟蹤調用和參數,如spyOn
,但沒有實現。
jasmine.createSpyObj
用於創建一個模擬,將窺探一個或多個方法。它返回一個對象,該對象對於每個間諜字符串都有一個屬性。
如果你想創建一個模擬,你應該使用jasmine.createSpyObj
。看看下面的例子。
從茉莉花文檔http://jasmine.github.io/2.0/introduction.html ...
createSpy:
describe("A spy, when created manually", function() {
var whatAmI;
beforeEach(function() {
whatAmI = jasmine.createSpy('whatAmI');
whatAmI("I", "am", "a", "spy");
});
it("is named, which helps in error reporting", function() {
expect(whatAmI.and.identity()).toEqual('whatAmI');
});
it("tracks that the spy was called", function() {
expect(whatAmI).toHaveBeenCalled();
});
it("tracks its number of calls", function() {
expect(whatAmI.calls.count()).toEqual(1);
});
it("tracks all the arguments of its calls", function() {
expect(whatAmI).toHaveBeenCalledWith("I", "am", "a", "spy");
});
it("allows access to the most recent call", function() {
expect(whatAmI.calls.mostRecent().args[0]).toEqual("I");
});
});
createSpyObj:
describe("Multiple spies, when created manually", function() {
var tape;
beforeEach(function() {
tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']);
tape.play();
tape.pause();
tape.rewind(0);
});
it("creates spies for each requested function", function() {
expect(tape.play).toBeDefined();
expect(tape.pause).toBeDefined();
expect(tape.stop).toBeDefined();
expect(tape.rewind).toBeDefined();
});
it("tracks that the spies were called", function() {
expect(tape.play).toHaveBeenCalled();
expect(tape.pause).toHaveBeenCalled();
expect(tape.rewind).toHaveBeenCalled();
expect(tape.stop).not.toHaveBeenCalled();
});
it("tracks all the arguments of its calls", function() {
expect(tape.rewind).toHaveBeenCalledWith(0);
});
});
很好的答案,但如果我想的方法'play'返回的東西是什麼?使用createSpyObj我無法模擬方法的行爲 – iberbeu
您可以使用tape.play.and.returnValue(1);請參閱[鏈接](http://jasmine.github.io/2.0/introduction.html#section-Spies:_
and.returnValue
)瞭解更多詳情。 –