开玩笑:禁用单元测试中的控制台的更好方法 [英] Jest: Better way to disable console inside unit tests

查看:106
本文介绍了开玩笑:禁用单元测试中的控制台的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的方法来禁用控制台错误 内部 特定的Jest测试(例如,还原原始控制台(每次测试之前/之后).

I wonder if there is a better way to disable console errors inside a specific Jest test (i.e., restore the original console before/after each test).

这是我目前的做法:

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似乎只能使用它.

Is there a cleaner way of accomplishing the same thing? I would like to avoid spyOn, but mockRestore only seems to work with it.

谢谢!

推荐答案

对于特定的规范文件,Andreas的文件就足够了.下面的设置将禁止所有测试套件的console.log语句

For particular spec file, Andreas's is good enough. Below setup will suppress console.log statements for all test suites,

jest --silent

(或)

要自定义warn, info and debug,您可以使用以下设置

To customize warn, info and debug you can use below setup

__ tests __/setup.js jest-preload.js

global.console = {
  log: jest.fn(), // console.log are ignored in tests

  // Keep native behaviour for other methods, use those to print out things in your own tests, not `console.log`
  error: console.error,
  warn: console.warn,
  info: console.info,
  debug: console.debug,
};

jest.config.js

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

Jest v24.x注意:不建议使用setupTestFrameworkScriptFile,而建议使用 setupFilesAfterEnv.

Jest v24.x Note: setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv.

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

这篇关于开玩笑:禁用单元测试中的控制台的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆