React 测试库 - 如何在测试时查看 DOM 的当前状态

3

我正在学习React测试库(在其他语言中有多年的TDD经验)。

React Testing Library文档中提到,当 getByText 失败时,“它会打印您正在测试的DOM状态”:

https://testing-library.com/docs/dom-testing-library/api-debugging/

enter image description here

但是,在我的当前RTL上并不会发生这种情况。

相反,我得到了这个:

  ● loads and displays greeting

    TestingLibraryElementError: Unable to find an element with the text: the current weather is: overcast clouds. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    Ignored nodes: comments, <script />, <style />
    <h1
      data-testid="currentWeatherOutput"
    />

      27 |   const currentWeatherOutput = screen.getByTestId('currentWeatherOutput')
      28 |
    > 29 |   getByText(currentWeatherOutput, "the current weather is: overcast clouds")

enter image description here

my package dependencies are

"dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "fetch": "^1.1.0",
    "msw": "^0.38.1",
    "node-fetch": "^3.2.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.2"
  },

我还有两个问题:

  1. 我能否在我的测试代码中直接跳入调试器?https://testing-library.com/docs/dom-testing-library/api-debugging/没有提及如何访问原生JS调试器。

  2. 我能否对DOM进行截屏(我猜不行,因为这实际上不是无头浏览器)并查看它?


从我所看到的,它确实被记录了:<h1 data-testid="currentWeatherOutput"/>。通过截图,您是指字面上的打印屏幕吗?还是更多地寻找快照?如果您展示测试用例文件,这也会对我们有所帮助。 - Tony
嗯...是的,但是DOM具有比<h1>标签更多的内容,所以我想这就是我感到困惑的原因。 - Jason FB
需要更多关于代码库的信息。例如,您是否使用react-testing library?如果没有,为什么不使用呢?或者您正在开发React Native应用程序,应该使用react-native testing library。我可以看到您使用了基本测试库函数中的screen,但是我没有看到您如何渲染任何组件。 - Tony
2个回答

13
我可以截取DOM的屏幕截图吗(我猜不能因为这不是无头浏览器)并查看它吗?
是的,你完全可以。看一下Jest Preview (https://github.com/nvh95/jest-preview)。
Jest Preview使你能够通过两行代码在浏览器中“看到”你的应用程序UI,而不是在终端中的HTML。
import { debug } from 'jest-preview';

describe('App', () => {
  it('should work as expected', () => {
    render(<App />);
    debug();
  });
});

很棒的库!你写的吗? - Son Nguyen

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接