我用于测试异步组件并useEffect
触发重新渲染的setState
方法是正常设置测试用例,但使用waitFor
orfindBy
阻止断言,直到组件使用获取的数据重新渲染。
这是一个简单的、可运行的示例:
import React, {useEffect, useState} from "react";
import {FlatList, Text} from "react-native";
import {render} from "@testing-library/react-native";
const Posts = () => {
const [posts, setPosts] = useState(null);
useEffect(() => {
const url = "https://jsonplaceholder.typicode.com/posts";
fetch(url).then(res => res.json()).then(setPosts);
}, []);
return !posts ? <Text>loading</Text> : <FlatList
testID="posts"
data={posts}
renderItem={({item: {id, title}, index}) =>
<Text testID="post" key={id}>{title}</Text>
}
/>;
};
describe("Posts", () => {
beforeEach(() => {
global.fetch = jest.fn(url => Promise.resolve({
ok: true,
status: 200,
json: () => Promise.resolve([
{id: 1, title: "foo title"},
{id: 2, title: "bar title"},
])
}));
});
it("should fetch posts", async () => {
const {findAllByTestId} = render(<Posts />);
const posts = await findAllByTestId("post", {timeout: 500});
expect(posts).toHaveLength(2);
expect(posts[0]).toHaveTextContent("foo title");
expect(posts[1]).toHaveTextContent("bar title");
expect(fetch).toHaveBeenCalledTimes(1);
});
});
这并没有给我任何act
警告,但我已经分享了这些。这个开放的 GitHub 问题似乎是规范资源。
使用的包:
{
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-native": "^0.64.0",
"react-native-web": "^0.15.6"
},
"devDependencies": {
"@babel/core": "^7.13.15",
"@testing-library/jest-native": "^4.0.1",
"@testing-library/react-native": "^7.2.0",
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
"metro-react-native-babel-preset": "^0.65.2",
"react-test-renderer": "^17.0.2"
}
}
在 Jest 配置中:
setupFilesAfterEnv: ["@testing-library/jest-native/extend-expect"],
为.toHaveTextContent
匹配器。或者您可以使用导入:
import "@testing-library/jest-native/extend-expect";