han*_*han 7 reactjs jestjs react-testing-library queryselector
我试图找到使用 React 测试库来测试 div 元素的 textContent 的最佳实践。
假设我想测试这个简单的 React 组件,看看它是否{props.text}在 HTML DOM 上正确呈现。
const Simple = props => (
<>
<div> {props.text} </div>
<div> test text </div>
</>
);
Run Code Online (Sandbox Code Playgroud)
我尝试使用getByText,然后进行测试expect(getByText('text passed as prop')).toBeDefined(),但它似乎无法正常工作。
<div />如果我为第一个添加一个 className 或 id ,那么可能我可以直接选择,那一定会容易得多querySelector,但是如果我不想在此处添加任何 HTML 属性怎么办?如何正确定位这个元素?
有什么解决方案可以找到第一个没有属性的元素并测试其内部文本吗?
它对我有用,使用"@testing-library/react": "^9.4.0". 例如
index.tsx:
import React from \'react\';\n\nconst Simple = (props) => (\n <>\n <div> {props.text} </div>\n <div> test text </div>\n </>\n);\n\nexport { Simple };\nRun Code Online (Sandbox Code Playgroud)\n\nindex.test.tsx:
import React from \'react\';\nimport { Simple } from \'./\';\nimport { render } from \'@testing-library/react\';\n\ndescribe(\'60534908\', () => {\n it(\'should find div element\', () => {\n const mProps = { text: \'text passed as prop\' };\n const { getByText } = render(<Simple {...mProps} />);\n expect(getByText(\'text passed as prop\')).toBeDefined();\n expect(getByText(\'test text\')).toBeDefined();\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n100%覆盖率的单元测试结果:
\n\n PASS stackoverflow/60534908/index.test.tsx (8.606s)\n 60534908\n \xe2\x9c\x93 should find div element (37ms)\n\n-----------|---------|----------|---------|---------|-------------------\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n-----------|---------|----------|---------|---------|-------------------\nAll files | 100 | 100 | 100 | 100 | \n index.tsx | 100 | 100 | 100 | 100 | \n-----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 9.784s, estimated 11s\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
14539 次 |
| 最近记录: |