我试图用jest和酶测试我的React组件。我有一个使用react-skylight
组件的表单组件。我在表单提交时触发.show()
函数,只是在服务器响应成功时触发。
我的测试目前是这样的:
import MyForm from './MyForm';
import Popup from 'react-skylight';
describe('<MyForm />', () => {
it('should show popup on success', () => {
const popupShowSpy = jest.spyOn(Popup.prototype, 'show');
const myForm = mount(<MyForm />);
myForm.update();
myForm.find('form').simulate('submit');
expect(popupShowSpy).toHaveBeenCalled();
});
});
但是当我运行测试时出现错误:
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.
我发现here对类似问题有所了解,但对我而言却无效。
解决方案:
axios
模块存在问题。它正在更新组件,但是模拟的响应没有得到解决,所以感谢这篇文章here,我设法编写了测试。并且我在父组件自己的函数中包装了子组件函数调用并且监视了那个父函数。
import MyForm from './MyForm';
import Popup from 'react-skylight';
describe('<MyForm />', () => {
it('should show popup on success', async() => {
const popupShowSpy = jest.spyOn(MyForm.prototype, 'showPopup');
const myForm = mount(<MyForm />);
const response = Promise.resolve({
data: {
message: 'Error: some error'
},
status: 400
});
axios.post = jest.fn(() => response);
myForm.find('form').simulate('submit');
await response;
myForm.update(); // <- child component is rendered correctly
expect(popupShowSpy).toHaveBeenCalled();
});
});
答案 0 :(得分:0)
解决方案:
axios
模块存在问题。它正在更新组件,但是被模拟的响应没有得到解决,所以感谢这篇文章here,我已经设法编写了测试。并且我在父组件自己的函数中包装了子组件函数调用并且监视了那个父函数。
import MyForm from './MyForm';
import Popup from 'react-skylight';
describe('<MyForm />', () => {
it('should show popup on success', async() => {
const popupShowSpy = jest.spyOn(MyForm.prototype, 'showPopup');
const myForm = mount(<MyForm />);
const response = Promise.resolve({
data: {
message: 'Error: some error'
},
status: 400
});
axios.post = jest.fn(() => response);
myForm.find('form').simulate('submit');
await response;
myForm.update(); // <- child component is rendered correctly
expect(popupShowSpy).toHaveBeenCalled();
});
});