Я тестирую (используя шутку, фермент) свой React.Component, в котором есть метод componentDidMount (), который я имитирую с помощью jest.spyOn (...). MockImplementation (...).
Ошибка, с которой я столкнулся, заключается в том, что этот фиктивный метод вызывается дважды - первый раз в исходной форме и второй раз в фиктивной. Может ли кто-нибудь помочь мне понять, почему это?
РЕШЕНИЕ путем перемещения jest.spyOn () в beforeEach (), но я не знаю, как компонент
под тестом
componentDidMount() {
this.getFiles();
}
getFiles() {
const $this = this;
console.log('check') //is logged
axios.get('http://localhost:8081/auth/files',
{withCredentials: true})
.then((response) => {
console.log('files'+response.data) //is not logged
this.setState({
images: response.data
},
function() { $this.imgList() }
);
});
}
тест
it('passes IMAGES, onCurrentImageChange, deleteImage, shouldGalleryOpen ' +
'as props to AuthPersonalBananasView', (done) => {
const mock = new MockAdapter(axios);
const resp = 'mock';
mock.onGet('http://localhost:8081/auth/files')
.reply(200, resp);
const mockIMAGES = [{
src: 'mock',
thumbnail: 'mock',
thumbnailWidth: 0,
thumbnailHeight: 0,
caption: 'mock',
tags: [{value: 'mock', title: 'mock'}]
}];
const mockShouldGalleryOpen = 'mock';
jest.spyOn(AuthPersonalBananas.prototype, 'componentDidMount')
.mockImplementation(() => {console.log('componentDidMount mock')});
component = mount(
<Provider store={store}>
<BrowserRouter>
<AuthPersonalBananas/>
</BrowserRouter>
</Provider>
);
component.find(AuthPersonalBananas).instance().setState({
IMAGES: mockIMAGES,
shouldGalleryOpen: mockShouldGalleryOpen
});
component.update();
setTimeout(function () {
expect(component.find(AuthPersonalBananasView).props().IMAGES)
.toEqual(mockIMAGES);
expect(component.find(AuthPersonalBananasView).props().onCurrentImageChange)
.toEqual(component.find(AuthPersonalBananas).instance().
onCurrentImageChange);
expect(component.find(AuthPersonalBananasView).props().deleteImage)
.toEqual(component.find(AuthPersonalBananas).instance()
.deleteImage);
expect(component.find(AuthPersonalBananasView).props().shouldGalleryOpen)
.toEqual(mockShouldGalleryOpen);
mock.restore();
done();
}, 500);
});