停止测试库的巨大错误输出

Ian*_*ger 8 react-testing-library angular-testing-library

我喜欢testing-library,在 React 项目中使用了很多,我现在正尝试在 Angular 项目中使用它 - 但我一直在努力解决巨大的错误输出,包括渲染的 HTML 文本。这不仅通常没有帮助(我找不到一个元素,这不是的 HTML );但如果您在调试模式下运行,它通常会在有趣的行之前被截断。

我只是将它作为一个库添加到标准的 Angular Karma+Jasmine 设置旁边。

如果 HTML 输出导致我的控制台窗口假脱机很长时间,我敢肯定你会说我正在测试的组件太大了,但是我在量角器中有很多集成测试,而且它们太慢了:(。

and*_*dak 6

我假设您在项目中使用 rtl 运行 jest。

我个人不会关闭它,因为它可以帮助我们,但每个人都有办法,所以如果你有你的理由,那就足够公平了。

1. 如果您想禁用特定测试的错误,您可以模拟console.error.

    it('disable error example', () => {

  const errorObject = console.error; //store the state of the object
  console.error = jest.fn(); // mock the object

  // code

  //assertion (expect)

  console.error = errorObject; // assign it back so you can use it in the next test
});
Run Code Online (Sandbox Code Playgroud)

2. 如果您想在所有测试中使其静音,您可以使用jest --silentCLI 选项。检查文档

以上甚至可能禁用由 rtl 完成的 DOM 打印,我不确定,因为我还没有尝试过,但是如果您查看我链接的文档,它会说

“防止测试通过控制台打印消息。”

现在,如果上述方法不起作用,除了 DOM 建议之外,您几乎可以肯定禁用了所有内容。在这种情况下,您可能会查看react-testing-library's源代码并找出用于这些打印语句的内容。是console.log吗?是console.warn吗?当你得到它时,就像上面的选项 1一样模拟它

更新

经过一番挖掘,我发现所有的testing-libraryDOM 打印都是建立在prettyDOM();

虽然prettyDOM()不能被禁用,但您可以将行数限制为 0,这只会给您错误消息和...消息下方的三个点。

这是一个示例打印输出,我搞砸了:

    TestingLibraryElementError: Unable to find an element with the text: Hello ther. 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.

...
Run Code Online (Sandbox Code Playgroud)

您需要做的就是在执行测试套件之前传入一个环境变量,因此例如使用 npm 脚本,它看起来像:

DEBUG_PRINT_LIMIT=0 npm run test
Run Code Online (Sandbox Code Playgroud)

这是文档

更新 2

根据github上的OP的FR,这也可以在不注入全局变量来限制PrettyDOM行输出的情况下实现(以防它在其他地方使用)。该getElementError配置选项需要改变:

dom-testing-library/src/config.js

     // called when getBy* queries fail. (message, container) => Error 
 getElementError(message, container) { 
   const error = new Error( 
     [message, prettyDOM(container)].filter(Boolean).join('\n\n'), 
   ) 
   error.name = 'TestingLibraryElementError' 
   return error 
 }, 
Run Code Online (Sandbox Code Playgroud)

也可以删除调用堆栈


Nei*_*ner 5

我会说最好的解决方案是使用该configure方法并传递一个自定义函数来getElementError执行您想要的操作。

您可以在此处阅读有关配置的信息:https : //testing-library.com/docs/dom-testing-library/api-configuration

这方面的一个例子可能如下所示:

configure({
  getElementError: (message: string, container) => {
    const error = new Error(message);
    error.name = 'TestingLibraryElementError';
    error.stack = null;
    return error;
  },
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其放在任何单个测试文件中,或使用 Jest 的setupFilessetupFilesAfterEnv配置选项使其全局运行。

  • 我上面的例子是 TypeScript,顺便说一句 - 如果你在非 TS 项目中使用 Jest 和 React,你可能不需要 `: string`! (2认同)