Hel*_*rld 14 javascript reactjs jestjs
我正在使用create-react-app并尝试编写一个检查console.log输出的jest测试
我的测试功能是:
export const log = logMsg => console.log(logMsg);
Run Code Online (Sandbox Code Playgroud)
我的测试是:
it('console.log the text "hello"', () => {
console.log = jest.fn('hello');
expect(logMsg).toBe('hello');
});
Run Code Online (Sandbox Code Playgroud)
这是我的错误
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.
Run Code Online (Sandbox Code Playgroud)
小智 39
或者你可以这样做:
it('calls console.log with "hello"', () => {
const consoleSpy = jest.spyOn(console, 'log');
console.log('hello');
expect(consoleSpy).toHaveBeenCalledWith('hello');
});
Run Code Online (Sandbox Code Playgroud)
JeB*_*JeB 17
如果你想检查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');
});
Run Code Online (Sandbox Code Playgroud)
在这里阅读更多.
另一种选择是保存对原始日志的引用,为每个测试替换一个笑话模拟,并在所有测试完成后恢复。这对不污染测试输出并仍然能够使用原始日志方法进行调试有一点好处。
describe("Some logging behavior", () => {
const log = console.log; // save original console.log function
beforeEach(() => {
console.log = jest.fn(); // create a new mock function for each test
});
afterAll(() => {
console.log = log; // restore original console.log after all tests
});
test("no log", () => {
// TODO: test something that should not log
expect(console.log).not.toHaveBeenCalled();
});
test("some log", () => {
// TODO: test something that should log
expect(console.log).toHaveBeenCalled();
const message = console.log.mock.calls[0][0]; // get log message
expect(message).toEqual(expect.stringContaining('something')); // assert on the message content
log(message); // actually log out what the mock was called with
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9501 次 |
| 最近记录: |