如何停止 Jest 在测试输出中包装 `console.log`?

Mar*_*nco 6 console.log jestjs

我正在根据请求进行 Jest 测试

describe("GET /user ", () => {
    test("It should respond with a array of users", done => {
        return request(url, (err, res, body) => {
            if (err) {
                console.log(err)
            } else {
                console.log("GET on " + url);
                body = JSON.parse(body);
                expect(body.length).toBeGreaterThan(0);
                done();
            }
        })
    })
});
Run Code Online (Sandbox Code Playgroud)

这很奇怪,因为在终端中,jest 将 console.log 行显示为输出的一部分:

 ...test output...

  console.log test/modules/user.test.js:18
    GET on https://xpto/api/user

...more test output...
Run Code Online (Sandbox Code Playgroud)

我需要隐藏该行:

console.log test/modules/user.test.js:18
Run Code Online (Sandbox Code Playgroud)

如何在 Jest 输出中隐藏 console.log 行?

And*_*gin 24

您可以将 Jest 的console实现替换为“普通”控制台,如下所示:

const jestConsole = console;

beforeEach(() => {
  global.console = require('console');
});

afterEach(() => {
  global.console = jestConsole;
});
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。模拟实现仅对完全禁用日志有用。此方法仅成功禁用 Jest 的跟踪。比你! (4认同)

Dor*_*nar 4

如果这是您编写的测试,为什么还需要记录错误?你可以依靠开玩笑的断言来做到这一点。如果您没有其他解决方案,您可以像这样
删除该函数:console.log

const log = console.log;
console.log = () => {};

/** Test logic goes here **/

console.log = log; // Return things to normal so other tests aren't affected. 

Run Code Online (Sandbox Code Playgroud)