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


当前回答

我发现上面的答案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被模拟,其他控制台方法不受影响。

其他回答

beforeAll(() => {
    jest.spyOn(console, 'log').mockImplementation(() => {});
    jest.spyOn(console, 'error').mockImplementation(() => {});
    jest.spyOn(console, 'warn').mockImplementation(() => {});
    jest.spyOn(console, 'info').mockImplementation(() => {});
    jest.spyOn(console, 'debug').mockImplementation(() => {});
});

我发现上面的答案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被模拟,其他控制台方法不受影响。

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

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

这里是你可能会用到的所有台词。你可以把它们放在测试中:

jest.spyOn(console, 'warn').mockImplementation(() => {});
console.warn("You won't see me!")
expect(console.warn).toHaveBeenCalled();
console.warn.mockRestore();

如果你使用命令npm test来运行测试,那么在包中更改测试脚本。像下面这样的Json

{
  ....
  "name": "....",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest --silent",         // add --silent to jest in script like this
    "lint": "eslint ."
  },
  ...
}

或者你可以在测试时直接运行命令npx jest——silent来清除所有日志和错误