用getByTestId,queryByTestId等获取到的元素为啥只能用innerHTML获取到文本内容,innerText不行

来源:6-5 测试驱动 - Menu 测试添加

菜鸟x

2021-07-19

用getByTestId,queryByTestId等获取到的元素为啥只能用innerHTML获取到文本内容,innerText不行,innerText是什么都获取不到。

function App() {
  return (
      <div className="App">
        <span data-testid="three">3</span>
        <span data-testid="four">4</span>
    </div>
  );
}

export default App;
import { render, screen } from '@testing-library/react';
import App from './App';

beforeEach(() => {
  render(<App />);
})

test('3 and 4 is on screen', () => {
  const { getByTestId } = screen
  const three = getByTestId('three')
  const four = getByTestId('four')
  expect(three).toBeVisible()
  expect(four).toBeVisible()
});
test('3 + 4 is 7', () => {
  const { getByTestId } = screen
  const three = parseInt(getByTestId('three').innerText)
  const four = parseInt(getByTestId('four').innerText)
  expect(three + four).toBe(7)
})

{
  "name": "todolist",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

写回答

2回答

张轩

2021-07-20

同学你好 

谢谢你的发现 我用你的代码在我这里也复现了 这个原因是 jsdom (jest 底层的一个用于模拟浏览器环境的库),它实现这个 innerText 有一个 bug,地址在:https://stackoverflow.com/questions/47902335/innertext-is-undefined-in-jest-test

因为 innerText 这个属性需要实际的浏览器的绘制功能来提供,而 js-dom 没有绘制的引擎,所以这个属性一直都会是 undefined。可以使用另外一个属性 textContent 代替。

0
2
菜鸟x
非常感谢!
2021-07-21
共2条回复

张轩

2021-07-19

同学你好 我这里是可以获取的 能否提供一下你的源代码 我在本地帮你看看为啥获取不到

0
1
菜鸟x
好的。代码已经写上了。
2021-07-19
共1条回复

React18+TS高仿AntD从零到一打造组件库

设计,开发,测试,发布再到 CI/CD,从0到1造轮子

2124 学习 · 959 问题

查看课程