Я пишу компонент, который применяет некоторую логику к событию resize.В основном это выглядит так:
class MyComponent extends React.Component {
componentDidMount() {
window.addEventListener('resize', this.handleWindowResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleWindowResize);
}
handleWindowResize = () => console.log('handleWindowResize');
}
Тест выглядит следующим образом:
it(`should do some stuff on window resize event`, () => {
const wrapper = mount(<MyComponent />);
const spy = jest.spyOn(wrapper.instance(), 'handleWindowResize');
wrapper.update();
global.dispatchEvent(new Event('resize'));
expect(spy).toHaveBeenCalled();
});
В моем журнале испытаний я получаю следующее сообщение FAIL:
console.log app/components/MyComponent/index.js:32
handleWindowResize
console.log app/components/MyComponent/index.js:32
handleWindowResize
console.log app/components/MyComponent/index.js:32
handleWindowResize
console.log app/components/MyComponent/index.js:32
handleWindowResize
console.log app/components/MyComponent/index.js:32
handleWindowResize
<CircleGraph /> › should do some stuff on window resize event
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called, but it was not called.
171 | global.dispatchEvent(new Event('resize'));
172 |
> 173 | expect(spy).toHaveBeenCalled();
| ^
174 | });
175 | });
176 |
Итак,исходная функция вызывается во время теста (функция работает без изъянов в исходном компоненте), но не в шпионе.Что я делаю неправильно?
Используя реакцию 16.6.0, jest-cli 23.6.0, фермент 3.7.0
[ОБНОВЛЕНИЕ] Я добавил проверенный метод в прототип с помощью this.handleWindowResize.bind(this)
в конструкторе и написалмой тест таков:
it(`should do some stuff on window resize event`, () => {
const spy = jest.spyOn(CircleGraph.prototype, 'handleWindowResize');
const wrapper = shallow(<MyComponent />);
global.dispatchEvent(new Event('resize'));
wrapper.unmount();
expect(spy).toHaveBeenCalled();
});
и шпион наконец вызвал.Хотя я не совсем уверен, почему ...