当我尝试对来自道具的函数使用expect spyOn时,我收到错误TypeError: Cannot assign to read only property 'onFocus' of object '#<Object>'
,可能是因为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 :(得分:0)
SpyOn尝试使用模拟覆盖您的方法。
用间谍替换目标中的方法。 https://github.com/mjackson/expect#spyon
但是你的对象是Enzyme提供的浅拷贝:
// That's what actually happens in your test, setup() aside
const wrapper = shallow(<AutoCompleteAsync {...props} />)
修改道具的唯一方法是再次调用setProps。
它(&#39; handleFocus&#39;,()=&gt; { const wrapper = setup() const props = { 价值:&#39;测试&#39;, onFocus :()=&gt; {} } //用spied onFocus替换onFocus const spy = spyOn(道具,&#39; onFocus&#39;)
// Inject spied onFocus back
wrapper.setProps(props)
wrapper.instance().handleFocus()
expect(spy).toHaveBeenCalled()
})