abh*_*and 4 javascript reactjs jestjs react-testing-library
我有一个组件可以异步获取数据 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({ .... });
})
;
}
Run Code Online (Sandbox Code Playgroud)
我对组件的测试如下所示 -
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();
});
Run Code Online (Sandbox Code Playgroud)
由于渲染和加载数据是异步的,我的expect()
语句会继续执行,componentDidMount()
然后假异步调用完成执行,因此expect()
语句总是失败。
我想我可以引入某种延迟,但这感觉不对,当然会增加我的测试运行时间。
这个类似的问题和这个要点片段都展示了我如何用酶测试这个。本质上,他们依靠async
/手动await
调用componentDidMount()
。
但是react-testing-library
似乎不允许直接访问组件以直接调用其方法(可能是设计使然)。所以我不确定要等待的“什么”,或者这是否是正确的方法。
谢谢!
这取决于您的组件在做什么。想象一下,您的组件显示一条加载消息,然后显示一条欢迎消息。您将等待欢迎消息出现:
const { getByText, findByText } = render(<MyComponent />)
expect(getByText('Loading...')).toBeInTheDocument()
expect(await findByText('Welcome back!')).toBeInTheDocument()
Run Code Online (Sandbox Code Playgroud)
考虑它的最好方法是打开浏览器查看您的组件。什么时候你知道它是装的?尝试在您的测试中重现它。
归档时间: |
|
查看次数: |
4409 次 |
最近记录: |