javascript - 在单元测试中禁用控制台的更好方法

标签 javascript jestjs

我想知道是否有更好的方法来禁用特定 Jest 测试中的控制台错误(即在每次测试之前/之后恢复原始控制台)。

这是我目前的做法:

describe("Some description", () => {
  let consoleSpy;

  beforeEach(() => {
    if (typeof consoleSpy === "function") {
      consoleSpy.mockRestore();
    }
  });

  test("Some test that should not output errors to jest console", () => {
    expect.assertions(2);

    consoleSpy = jest.spyOn(console, "error").mockImplementation();
 
    // some function that uses console error
    expect(someFunction).toBe("X");
    expect(consoleSpy).toHaveBeenCalled();
  });

  test("Test that has console available", () => {
    // shows up during jest watch test, just as intended
    console.error("test");
  });
});

是否有更简洁的方法来完成同样的事情?我想避免 spyOn,但 mockRestore 似乎只适用于它。

最佳答案

对于特定的规范文件,Andreas 的已经足够好了。下面的设置将抑制所有测试套件的 console.log 语句,

jest --silent

(或)

要自定义警告、信息和调试,您可以使用以下设置

tests/setup.js jest-preload.jssetupFilesAfterEnv

global.console = {
  ...console,
  // uncomment to ignore a specific log level
  log: jest.fn(),
  debug: jest.fn(),
  info: jest.fn(),
  // warn: jest.fn(),
  // error: jest.fn(),
};

jest.config.js

module.exports = {
    verbose: true,
    setupFilesAfterEnv: ["<rootDir>/__tests__/setup.js"],
};

关于javascript - 在单元测试中禁用控制台的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44467657/

相关文章:

javascript - 如何将函数返回插入innerHTML

javascript - Jest 方法调用计数错误?

reactjs - Jest 测试失败,警报未定义

unit-testing - 当模块未模拟时,如何在 Jest 中模拟导入的命名函数

unit-testing - 如何在每个测试中以不同的方式模拟克隆的导入依赖项

javascript - React Native - 当键盘处于打开状态时 BackHandler 不工作

javascript - 正则表达式匹配不带引号的字符串,但不匹配 CSV 中的数字

javascript - nodejs加载文件

javascript - WinRT 语言投影如何针对 JavaScript 详细工作?

reactjs - 测试 React 组件方法正在调用函数 pass 作为 prop