你可以有多个testID
s。不然就不会有__AllByTestId
选择器。这个名字似乎没有经过深思熟虑,因为它与 HTML id 相似,而 HTML id 必须是唯一的。
如果您使用,则会发生抛出__ByTestId
但您有多个具有匹配测试 id 的元素:
it("getByTestId will throw with multiple testIDs", () => {
const {getAllByTestId, getByTestId} = render(
<View>
<Text testID="foo">a</Text>
<Text testID="foo">b</Text>
</View>
);
expect(getAllByTestId("foo")).toHaveLength(2); // OK
getByTestId("foo"); // => Error: Found multiple elements with testID: foo
});
要测试地图,您可以向子级添加测试 ID 并使用上述模式。
反应本机:
import "@testing-library/jest-native/extend-expect";
// ...
it("should find text content in all children", () => {
const {getAllByTestId} = render(
<View>
{[..."abcd"].map((e, i) =>
<View key={e + i} testID="foo"><Text>{e}</Text></View>
)}
</View>
);
expect(getAllByTestId("foo")).toHaveLength(4);
[..."abcd"].forEach((e, i) => {
expect(getAllByTestId("foo")[i]).toHaveTextContent(e);
});
});
React:
it("should find text content in all children", () => {
const {getAllByTestId} = render(
<ul>
{[..."abcd"].map((e, i) =>
<li key={e + i} data-testid="foo">{e}</li>
)}
</ul>
);
expect(getAllByTestId("foo")).toHaveLength(4);
[..."abcd"].forEach((e, i) => {
expect(getAllByTestId("foo")[i].textContent).toEqual(e);
});
// or:
//const contents = getAllByTestId("foo").map(e => e.textContent);
//expect(contents).toEqual([..."abcd"]);
});
还可以添加一个testID
到映射列表元素的父级,选择父级,然后遍历其.children
数组对每个子树进行断言。
注意之间的差异testID
在注册护士和data-testid
在反应中。
顺便说一句,我不确定
expect(getByTestId('side-menu-link')).toHaveAttribute('User Preferences')
这里很有意义。属性是<div this_is_an_attribute="foo">
-- 您可能正在寻找文本内容。
使用的包,供参考:
反应本机
{
"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"
}
}
React
{
"dependencies": {
"@babel/runtime": "7.10.5",
"react": "16.13.1",
"react-dom": "16.13.1",
},
"devDependencies": {
"@babel/core": "7.10.5",
"@babel/plugin-proposal-class-properties": "7.10.4",
"@babel/preset-env": "7.10.4",
"@babel/preset-react": "7.10.4",
"@testing-library/dom": "7.21.0",
"@testing-library/jest-dom": "^5.11.1",
"@testing-library/react": "10.4.7",
"@testing-library/react-hooks": "3.3.0",
"@testing-library/user-event": "12.0.11",
"babel-jest": "26.1.0",
"jest": "26.1.0",
"jest-environment-jsdom": "26.1.0",
"react-test-renderer": "16.13.1",
}
}