问题描述
我有一个带有请求我的api方法的react组件。 为了进行测试,我嘲笑了模块。 确实会用get识别第一个调用,但不能识别带post的第二个调用,除非它在get语句之前声明。 我可以记录到axios.post.mock.result在我的react组件中有一个价值承诺。 在我的测试中,它是空的。 我这样隔离问题:
我的组件方法
import axios from 'axios'; async getData(data) { let response = await axios.get('/api', { params: { data } }); if (response.status === 200) { response = await axios.post('/api', response.data ); if (response.status === 200) { this.setState({ data: true }); } } } render() { if (!this.state.data) { return ( <button onClick={() => this.getData(this.state.input)} >Click me</button>) } else { return (<p>Success</p>); }
考试
import {render, fireEvent} from 'react-testing-library'; import axios from 'axios'; import App from '../App'; jest.mock('axios'); axios.get.mockResolvedValue({ status: 200, data: { hello: 'world' } }); axios.post.mockResolvedValue({ status: 200 }); test('Component uses axios', () => { let app = render(<App />); fireEvent.click(app.getByText('Click me')); expect(axios.get).toBeCalled(); expect(axios.post).toBeCalled(); });
1楼
Estus Flask
0
已采纳
2019-02-21 11:43:44
react-testing-library主要用于黑盒功能测试,不适合测试实现。 常见的测试策略是模拟点击并声明DOM:
const { getByText } = render(<App />);
fireEvent.click(app.getByText('Click me'));
await waitForElement(() => getByText('Success'));
可以通过实现断言来强制执行该测试。
axios.post被异步调用,并且它返回的承诺应该被链接起来:
...
fireEvent.click(app.getByText('Click me'));
expect(axios.get).toBeCalledTimes(1);
await axios.get.mock.results[0].value;
expect(axios.post).toBeCalledTimes(1);
await waitForElement(() => getByText('Success'));