我怎样才能停止Jest在测试输出中 Package 'console. log'?

amrnrhlw  于 2022-12-08  发布在  Jest
关注(0)|答案(5)|浏览(290)

我在做一个玩笑测试

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();
            }
        })
    })
});

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

...test output...

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

...more test output...

我需要隐藏行:

console.log test/modules/user.test.js:18

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

0dxa2lsx

0dxa2lsx1#

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

const jestConsole = console;

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

afterEach(() => {
  global.console = jestConsole;
});
ovfsdjhp

ovfsdjhp2#

If it's a test you've written, why do you even need to log the error? You can rely on jest assertions for that.
If you have no other solution, you can stub out the console.log function like so:

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

/** Test logic goes here **/

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

egdjgwm83#

您可以使用jest.spyOn来模拟console方法:

const spy = jest.spyOn(console,'warn').mockReturnValue()

// after you are done with the test, restore the console
spy.mockRestore()

您可以创建一个实用函数来模拟console

function mockConsole(method = 'warn', value){
    return jest.spyOn(console,method).mockReturnValue(value).mockRestore
}

const restore = mockConsole() //mock it

// later when you are done
restore() // unmock it

此外,您还可以将上述代码答案与jest. beforeEach结合使用,以自动恢复console

beforeEach(()=>{
    // beware that this will restore all mocks, not just the console mock
    jest.restoreAllMocks()
})
snvhrwxg

snvhrwxg4#

您需要使用process.stdout.write创建自己的日志函数,或者使用它来代替console.log,因为jest正在监视所有控制台函数。
之前我一直在尝试为Typescript引入一个我非常喜欢的Scala实用程序;我不明白为什么jest打印这些“consol.log + line”,这没有意义,因为你可以很容易地用Crt + Find找到它们,而且没有选项可以用--silent和--verbose=false选项关闭它们(当然silent可以工作,但它会删除所有日志,所以这有什么意义)。
最后,我想到了:

const colors = require('colors');

const testLog = (str : string) => process.stdout.write(str)

export const Given = (givenMsg: string) => testLog(`\n+ Given ${givenMsg}\n`)
export const When = (whenMsg: string) => testLog(`+ When ${whenMsg}\n`)
export const Then = (thenMsg: string) => testLog(`+ Then ${thenMsg}\n`)
export const And = (andMsg: string) => testLog(`- And ${andMsg}\n`)

export const testCase = (description: string, testFunction: Function) => it (description, () => {
    testLog(colors.yellow(`\n\nTest: ${description}\n`))
    testFunction()
    testLog('\n')
})

看上去是这样的:
given when then typescript

zaqlnxep

zaqlnxep5#

你可以试着用“沉默”来开玩笑。
在package.json中,使用两个脚本:

"scripts": {
   "test": "jest --silent",
   "testVerbose": "jest"
},

相关问题