2012-08-01 43 views
0

我如何告訴茉莉間諜只聽我告訴它的信息,期望並忽略其他人?防止茉莉間諜聆聽不當信息

例如:

例組

describe 'View', -> 
    describe 'render', -> 
    beforeEach -> 
     @view = new View 
     @view.el = jasmine.createSpyObj 'el', ['append'] 
     @view.render() 

    it 'appends the first entry to the list', -> 
     expect(@view.el.append).toHaveBeenCalledWith '<li>First</li>' 

    it 'appends the second entry to the list', -> 
     expect(@view.el.append).toHaveBeenCalledWith '<li>Second</li>' 

實施

class View 
    render: -> 
    @el.append '<li>First</li>', '<li>Second</li>' 

輸出

View 
    render 
    appends the first entry to the list 
     Expected spy el.append to have been called \ 
     with [ '<li>First</li>' ] but was called \ 
     with [ [ '<li>First</li>', '<li>Second</li>' ] ] 

    appends the second entry to the list 
     Expected spy el.append to have been called \ 
     with [ '<li>Second</li>' ] but was called \ 
     with [ [ '<li>First</li>', '<li>Second</li>' ] ] 

回答

1

有兩個選項:

1.使用argsForCall間諜屬性

it 'appends the first entry to the list', -> 
    expect(@view.el.append.argsForCall[0]).toContain '<li>First</li>' 

2.使用mostRecentCall對象的屬性args

it 'appends the first entry to the list', -> 
    expect(@view.el.append.mostRecentCall.args).toContain '<li>First</li>' 
0

要清楚,你無法阻止間諜傾聽。間諜會監聽所有的功能調用並保存。但是,您可以通過使用argsForCall來超過每個呼叫。

+0

感謝您的回答,** Andreas **。我在我的回答中已經寫了關於'argsForCall'的信息。如果您熟悉RSpec Ruby BDD框架,您可能知道它定義了['as_null_object'](https://www.relishapp.com/rspec/rspec-mocks/v/2-6/docs/method-存根/ as-null-object)方法爲雙打。這些雙打將忽略你不存在的任何其他消息,而雙打在收到這些消息時不會引發任何異常。我認爲Jasmine具有類似的功能,像'jasmine.createSpyObj('Object',['method'])。as_null_object()'。 – Shamaoke 2012-08-03 12:51:00