我有一个执行以下操作的父组件:
input
字段的表单POST
向服务器发出一个<form>
数据的axios
请求Error
响应,则会在表单上的<span>
元素内显示错误消息我正在针对这种情况编写以下测试
import axios from 'axios';
import { expect } from 'chai';
import { mount } from 'enzyme';
jest.mock('axios');
it('displays an error when the submit fails', async () => {
const wrapper = mount(<MyComponent />);
// Fill in form input fields with text (not shown)
// ....
// ....
// Mock the axios `POST` call to return an error
const errorResponse = { response: { data: { errors: [{ title: 'Some error' }] } } }
axios.post.mockImplementationOnce(() => Promise.reject(errorResponse));
// Click Submit and wait on the axios Promise to complete
const submit = wrapper.find('.my-component__submit-btn').first();
await submit.simulate('click');
// Check if error was rendered on the form
wrapper.update();
const error = wrapper.find('.my-component__submit-error').first();
expect(error).to.have.text('Some error'); // This fails!
});
最后一个expect()
失败-未设置任何错误,但我希望它存在。
但是,如果我通过setTimeout
添加了人为的延迟,它就会过去。显然,这是一个问题,即React组件树在expect()
检查之前没有更新。
是否有一种干净的方法可以在React树上“等待”以重新渲染而无需使用setTimeout
?
我认为wrapper.update()
会这样做,但似乎没有。
谢谢!
答案 0 :(得分:0)
有一种方法可以等待所有 Promise 得到解决。 定义:
message.author.username
然后,在组件渲染完成后,等待:
tempfile.NamedTemporaryFile()
这虽然在大多数情况下有效,但如果组件在内部更新其状态,而不从其属性触发这些状态更新,则这仍然不起作用。
我相信当是后者时,这只是一种不可测试的模式,需要改变应用程序设计方法,而不是测试方法。