2012-08-01 54 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