2014-06-20 31 views
25

我在我的代碼中使用過。createspy和createspypyj有什麼區別

return $provide.decorator('aservice', function($delegate) { 
      $delegate.addFn = jasmine.createSpy().andReturn(true); 
      return $delegate; 
     }); 

在那個什麼createSpy做?我可以將createSpy調用更改爲createspypyj調用。

通過使用createSpy,我們可以創建一個函數/方法mocks。 Createspyobj可以執行多個功能模擬。我對嗎?

會有什麼區別。

回答

50

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); 
    }); 
}); 
+0

很好的答案,但如果我想的方法'play'返回的東西是什麼?使用createSpyObj我無法模擬方法的行爲 – iberbeu

+7

您可以使用tape.play.and.returnValue(1);請參閱[鏈接](http://jasmine.github.io/2.0/introduction.html#section-Spies:_ and.returnValue)瞭解更多詳情。 –