react-testing-library: 调试输出的某些部分不可见

170
我正在使用React Jest和React Testing Library来测试我的组件。 我遇到了一个奇怪的问题。我正在使用由testing-library的render返回的debug函数。
test('component should work', async () => {
  const { findByText, debug } = render(<MyComponent />);
  const myElement = await findByText(/someText/i);
  debug();

});

enter image description here

如您在截图中所见,有一些未完成的div和缺失父级闭合标签。

7
你尝试过按照这里提到的方法增加DEBUG_PRINT_LIMIT吗? - uday
1
@uday,使用DEBUG_PRINT_LIMIT仍然没有运气,问题依旧。 - Amit Chauhan
你可以通过以下方式实现:screen.debug(myComponent, Infinity)。注意:你可以指定“undefined”而不是“myComponent”来调试整个文档。 - Daniel Peña
12个回答

149

2
如果这对其他人不起作用,请注意这个限制是打印的字符数,而不是行数。 - Eric Majerus

140

我正在使用这个版本:"@testing-library/react": "^11.0.4"

我们可以像下面这样做,将300000更改为输出的最大长度。

debug(undefined, 300000)  

1
debug(undefined, 300000) - J. Munson
@J.Munson 为什么是 undefined - byxor
2
基本上是为了让 TypeScript 快乐。但通常情况下,在 JavaScript 中省略参数的标准方式是使用 undefined - J. Munson
你在哪个(文件)调用这个函数? - DarkTrick
answered below by @labs - bzk

76

Another option

screen.debug(undefined, Infinity);


38

18

你可以使用 Jest Preview (https://github.com/nvh95/jest-preview) 来在浏览器中查看应用程序的用户界面,而不是在终端中查看 HTML,只需两行代码即可:

import { debug } from 'jest-preview';

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

Jest Preview 调试 React 测试库

它与 jestreact-testing-library 配合得非常好。


1
非常有趣 - marko kraljevic
它不适用于React Native,而是使用jsdom和document。 - Greg Wozniak
哇,真棒✨。对于刚开始的人来说,请注意你还必须运行jest-preview服务器才能使其正常工作。 - undefined

8

由于DOM的大小可能非常大,您可以通过环境变量DEBUG_PRINT_LIMIT设置要打印的DOM内容限制。默认值为7000。当DOM内容被剥离(因为您设置的长度或由于默认大小限制)时,您将在控制台上看到...。以下是在运行测试时如何增加此限制的方法:

DEBUG_PRINT_LIMIT=10000 npm test

文档中有更多关于调试的信息。


这对我有用,只需将此代码放在我的测试之前 DEBUG_PRINT_LIMIT=10000 pnpm test "文件路径" - Purple_Kitten

6
如果其他答案都不适用于您,请确保不是终端限制。例如,VS Code仅在缓冲区中保留5000行。请尝试Mac OS终端。

5

这对我有用:

debug(undefined, 300000);

它将为您提供传递到 render() 中的任何内容的标记:
import {render, screen} from '@testing-library/react'

render(<MyComponent />);

您可以阅读更多有关协助您打印结果的方法,包括美化生成的标记,详见:

debug 的API文档


1
我添加了 screen 以使其按照我的需要工作:screen.debug(undefined, 300000); - Purple_Kitten

3

这对我有用

const history = createMemoryHistory()
const { debug } = renderWithRedux(
    <Router history={history}>
        <SideBar />
    </Router>
, state);

screen.debug(debug(), 20000);

1

默认情况下,RTL不显示注释、<script /><style />标签。在我的情况下,我需要测试DOM中的已注释节点。

如果您希望测试包括所有节点,可以像这样使用prettyDOM

// render DOM with a commented node
const html = {__html: '<!--this is a commented DOM element-->'};
const element = <div dangerouslySetInnerHTML={html} />;
const { container } = render(element);

// This is what tells RLT to print all nodes!
const prettyfiedDOM = prettyDOM(container, undefined, { filterNode: () => true}) || '';

expect(prettyfiedDOM.includes('<!--this is a commented DOM element-->')).toBeTruthy();

请注意,filterNode函数始终返回true,这告诉RTL打印所有DOM节点,因此您可以测试注释、样式、标签等。您可以在prettyDOM源代码上阅读更多信息,并配置所需的DOM过滤行为

在此查看实时演示

希望能有所帮助!


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