我想知道是否有更好的方法在特定的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似乎只与它一起工作。


当前回答

因为笑话。我开玩笑地说:“间谍在这方面行不通(过去可能有用)。”fn使用Jest文档中指出的手动模拟恢复。这样,您就不会错过任何在特定测试中没有被经验忽略的日志。

const consoleError = console.error beforeEach(() => { 控制台。error = consoleError }) Test('错误',()=> { 控制台。Error = jest.fn() Console.error ('error') //无法看到我 }) 测试('有错误和日志',()=> { Console.error ('error') //现在可以 })

其他回答

对我来说,一个更清晰/干净的方式(读者需要很少的笑话API知识来理解发生了什么),就是手动做mockRestore所做的事情:

// at start of test you want to suppress
const consoleLog = console.log;
console.log = jest.fn();

// at end of test
console.log = consoleLog;

另一种方法是使用process.env.NODE_ENV。通过这种方式,在运行测试时可以选择性地选择显示(或不显示)什么:

if (process.env.NODE_ENV === 'development') {
  console.log('Show output only while in "development" mode');
} else if (process.env.NODE_ENV === 'test') {
  console.log('Show output only while in "test" mode');
}

or

const logDev = msg => {
  if (process.env.NODE_ENV === 'development') {
    console.log(msg);
  }
}
logDev('Show output only while in "development" mode');

这将需要将这个配置放在package.json中:

"jest": {
  "globals": {
    "NODE_ENV": "test"
  }
}

注意,这种方法不是原始问题的直接解决方案,但只要有可能用上述条件包装console.log,就会给出预期的结果。

如果你只是想做一个特定的测试:

beforeEach(() => {
  jest.spyOn(console, 'warn').mockImplementation(() => {});
});

向@Raja的最佳答案致敬。这是我正在使用的(我会注释,但不能在注释中共享多行代码块)。

与jest v26,我得到这个错误:

We detected setupFilesAfterEnv in your package.json.

Remove it from Jest configuration, and put the initialization code in src/setupTests.js:
This file will be loaded automatically.

因此,我不得不从我的jest配置中删除setupFilesAfterEnv,并将其添加到src/setupTests.js中

// https://stackoverflow.com/questions/44467657/jest-better-way-to-disable-console-inside-unit-tests
const nativeConsoleError = global.console.error

global.console.error = (...args) => {
  if (args.join('').includes('Could not parse CSS stylesheet')) {
    return
  }
  return nativeConsoleError(...args)
}

我发现上面的答案re:在所有测试套件中抑制console.log在调用任何其他控制台方法(例如warn, error)时抛出错误,因为它正在替换整个全局控制台对象。

这种有点类似的方法适用于我的Jest 22+:

package.json

"jest": {
  "setupFiles": [...],
  "setupTestFrameworkScriptFile": "<rootDir>/jest/setup.js",
  ...
}

是/设置.js

jest.spyOn(global.console, 'log').mockImplementation(() => jest.fn());

使用此方法,只有console.log被模拟,其他控制台方法不受影响。