【发布时间】:2020-01-20 00:34:02
【问题描述】:
我有一个组件在componentDidMount() 中异步获取数据
componentDidMount() {
const self = this;
const url = "/some/path";
const data = {}
const config = {
headers: { "Content-Type": "application/json", "Accept": "application/json" }
};
axios.get(url, data, config)
.then(function(response) {
// Do success stuff
self.setState({ .... });
})
.catch(function(error) {
// Do failure stuff
self.setState({ .... });
})
;
}
我对组件的测试如下所示 -
it("renders the component correctly", async () => {
// Have API return some random data;
let data = { some: { random: ["data to be returned"] } };
axios.get.mockResolvedValue({ data: data });
const rendered = render(<MyComponent />);
// Not sure what I should be awaiting here
await ???
// Test that certain elements render
const toggleContainer = rendered.getByTestId("some-test-id");
expect(toggleContainer).not.toBeNull();
});
由于渲染和加载数据是异步的,我的 expect() 语句会在 componentDidMount() 之前执行并执行假异步调用,因此 expect() 语句总是失败。
我想我可以引入某种延迟,但这感觉不对,当然会增加我的测试运行时间。
This similar question 和 this gist snippet 都展示了我如何使用 Enzyme 进行测试。本质上,他们依靠async/await 手动调用componentDidMount()。
但是react-testing-library 似乎不允许直接访问组件以直接调用其方法(可能是设计使然)。所以我不确定要等待“什么”,或者这是否是正确的方法。
谢谢!
【问题讨论】:
标签: javascript reactjs jestjs react-testing-library