私は使用していますReactアプリを作成するそして書こうとしている冗談の出力をチェックするテストconsole.log
。
テストする機能は次のとおりです:
export const log = logMsg => console.log(logMsg);
私のテストは次のとおりです:
it('console.log the text "hello"', () => {
console.log = jest.fn('hello');
expect(logMsg).toBe('hello');
});
これが私の間違いです
FAIL src/utils/general.test.js
● console.log the text hello
expect(received).toBe(expected) Expected value to be (using ===): "hello"
Received:
undefined
Difference:
Comparing two different types of values. Expected string but received undefined.
ベストアンサー1
console.log
が正しいパラメータ(渡したパラメータ)を受け取ったかどうか確認したい場合は、mock
をチェックする必要がありますjest.fn()
。
また、関数を呼び出す必要もあります。log
そうしないと、console.log
は呼び出されません。
it('console.log the text "hello"', () => {
console.log = jest.fn();
log('hello');
// The first argument of the first call to the function was 'hello'
expect(console.log.mock.calls[0][0]).toBe('hello');
});
または
it('console.log the text "hello"', () => {
console.log = jest.fn();
log('hello');
// The first argument of the first call to the function was 'hello'
expect(console.log).toHaveBeenCalledWith('hello');
});
この方法を採用する場合は、 の元の値を復元することを忘れないでくださいconsole.log
。
別のオプションはjest.spyOn
、(を置き換える代わりに、console.log
それに対するプロキシを作成する)を使用することです。
it('console.log the text "hello"', () => {
const logSpy = jest.spyOn(console, 'log');
console.log('hello');
expect(logSpy).toHaveBeenCalledWith('hello');
});
続きを読むここ。