【问题标题】:How do I prevent node from sending errors to the console?如何防止节点向控制台发送错误?
【发布时间】:2021-02-27 03:37:18
【问题描述】:

从事 React 项目。

我使用npm start 启动我的环境。然后我在另一个终端中使用npm test 启动我的测试基础设施。在我的测试运行时,会在运行我的环境的终端中生成并打印错误。

  1. npm start
Compiled successfully!

You can now view v2 in the browser.

  Local:            http://localhost:3000

Note that the development build is not optimized.
To create a production build, use yarn build.
  1. 打开另一个终端并运行npm test
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        2.415s
Ran all test suites.
  1. 然而,测试生成的一些 UI 错误出现在我本地环境的终端中
Compiled successfully!

You can now view v2 in the browser.

  Local:            http://localhost:3000

Note that the development build is not optimized.
To create a production build, use yarn build.

[HPM] Error occurred while trying to proxy request /directory from localhost:3000 to <TARGET> (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
[HPM] Error occurred while trying to proxy request /directory from localhost:3000 to <TARGET> (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
[HPM] Error occurred while trying to proxy request /directory from localhost:3000 to <TARGET> (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
[HPM] Error occurred while trying to proxy request /directory from localhost:3000 to <TARGET> (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
[HPM] Error occurred while trying to proxy request /directory from localhost:3000 to <TARGET> (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)

我如何防止错误 - 以及与此相关的任何其他内容 - 被打印到我启动开发环境的终端?

【问题讨论】:

  • 什么操作系统? npm start &gt;&amp; log.txt(或npm start &gt;&amp; /dev/null,如果您更喜欢在出现问题时处于黑暗中)可以在 Linux 上运行。
  • macOS,我用我遇到的错误更新了我的帖子。你知道是否有办法专门忽略以[HPM] 开头的行吗?我的目标是仍然打印Compiled successfully... 部分,但不打印以[HPM] 开头的任何内容。
  • npm start |& grep -v '[HPM]'

标签: npm npm-scripts


【解决方案1】:

查看您的npm test 的输出,您似乎在使用jest,它支持configuring setup files

在执行套件中的每个测试文件之前运行一些代码以配置或设置测试框架的模块的路径列表。

您可以通过指向一个文件来使用它,您可以在其中将mock the implmentation 用于console

将以下内容添加到jest.config.js

module.exports = {
  setupFilesAfterEnv: ['./jest.setup.js'],
};

然后在jest.setup.js文件中

global.beforeAll(() => {
  // disable console.error for clarity
  console.error = jest.fn().mockImplementation(() => {});
});

请注意,只有在测试期间打印到控制台的模块使用console.error() 时,它才会达到您的期望。否则,您可能需要模拟其他函数,例如console.info()console.log()console.debug()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2012-04-22
    • 2021-06-09
    • 2020-12-16
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多