2016-12-02 44 views
1

我得到一個錯誤TypeError: Cannot assign to read only property 'onFocus' of object '#<Object>'當我嘗試,可能是因爲spyOn行爲,以便使用期望從道具的功能spyOn。使用mjackson的期望spyOn的功能從陣營組件的道具

it('handleFocus',() => { 
     const wrapper = setup() 
     const spy = spyOn(wrapper.props(), 'onFocus') 
     wrapper.instance().handleFocus() 
     expect(spy).toHaveBeenCalled() 
}) 

有設置功能

const setup = (isMount) => { 
    const props = { 
     value: 'test', 
     promise:() => Promise.resolve({}), 
     access:() => {}, 
     onFocus:() => {}, 
     onChange:() => {}, 
     onUpdateInput: v => v 
    } 
    return isMount 
     ? mount(<AutoCompleteAsync {...props} />) 
     : shallow(<AutoCompleteAsync {...props} />) 
    } 

在那裏你可以找到handleFocus功能

handleFocus() { 
    const { onFocus, onInputFocus } = this.props 
    if (onInputFocus) { 
     onInputFocus() 
    } 
    onFocus() 
    } 

回答

0

SpyOn試圖用模擬重寫你的方法。

替換爲間諜在靶的製造方法。 https://github.com/mjackson/expect#spyon

但你的對象是一個淺拷貝酶提供:

// That's what actually happens in your test, setup() aside 
const wrapper = shallow(<AutoCompleteAsync {...props} />) 

修改其道具的唯一方法是再次調用setProps。

它( 'handleFocus',()=> { const的包裝=設置() const的道具= { 值: '測試', 的onfocus:()=> {} } //替換的onfocus與窺探的onfocus 常量間諜= spyOn(道具, '聚焦狀態')

// Inject spied onFocus back 
    wrapper.setProps(props) 
    wrapper.instance().handleFocus() 
    expect(spy).toHaveBeenCalled() 

})

+0

遺憾的是它並沒有幫助,我也有同樣的錯誤。 –

+0

錯過了你安裝該組件的事實。更新了我的答案。 –

+0

但我並不在本次測試(無處,實際上現在)安裝它。你的答案也沒有改變? –