我有一个 React 组件MyComponent
,我想在其中测试用户旋转手机时应该触发的行为。
组件内部:
export class MyComponent extends React.PureComponent<props> {
componentDidMount() {
window.addEventListener('orientationchange', this.onRotation)
}
componentWillUnmount() {
window.removeEventListener('orientationchange', this.onRotation)
}
onRotation = () => {
// do things
}
render() {
// ...
}
}
我在 medium 上找到了一篇文章,描述了如何为此编写测试。但是,这对我不起作用。
describe('<MyComponent />', () => {
it('does things on rotation', () => {
const map : any = {}
window.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
})
const wrapper : any = mount(<MyComponent />)
map.orientationchange()
expect(wrapper.onRotation).toHaveBeenCalled()
})
})
在文章中这有效,但是我收到一个错误:
"Matcher error: received value must be a mock or spy function
Received has value: undefined"
使用间谍也不起作用:
it('does things on rotation', () => {
const map : any = {}
window.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
})
const wrapper : any = mount(<MyComponent />)
const spy = jest.spyOn(wrapper.instance(), 'onRotation')
map.orientationchange()
expect(spy).toHaveBeenCalled()
})
它说:
"Expected mock function to have been called, but it was not called."