У меня есть React Component MyComponent
, где я хочу протестировать поведение, которое должно срабатывать, когда пользователь поворачивает свой телефон.
Внутри компонента:
export class MyComponent extends React.PureComponent<props> {
componentDidMount() {
window.addEventListener('orientationchange', this.onRotation)
}
componentWillUnmount() {
window.removeEventListener('orientationchange', this.onRotation)
}
onRotation = () => {
// do things
}
render() {
// ...
}
}
Я нашелстатья на носителе, которая описывает, как написать тесты для этого здесь .Однако, это не работает для меня.
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."