How to mock console.log in Jest JS

334 Views Asked by At

I am doing testing using JEST in npm. Below is scenarios

I have a TestScript.js file

function someComplexFunction() {
  console.log("some important message");
}

module.exports = someComplexFunction

to test this function in there in TestScript.test.js file

const someComplexFunction = require("./TestScript")


test('Console log should have been called', () => {
    const logSpy = jest.spyOn(console, 'log');

    someComplexFunction();
    
    expect(logSpy).toHaveBeenCalledWith('some important message');
    
    logSpy.mockRestore();
});

when I am runnig the test I getting failure

npm test

Console log should have been called

    expect(jest.fn()).toHaveBeenCalledWith(...expected)

    Expected: "some important message"

    Number of calls: 0

      32 |      someComplexFunction();
      33 |
    > 34 |      expect(logSpy).toHaveBeenCalledWith('some important message');
         |                     ^
      35 |
      36 |      logSpy.mockRestore();
      37 | });

      at Object.toHaveBeenCalledWith (src/test/TestScript.test.js:34:17)

Please let me know what I am making mistake, why mocking is not working.

I tried changing the spyOn function but still not working, also tried with warn but still no luck.

3

There are 3 best solutions below

0
On

Finally it worked in this way:

const someComplexFunction = require("./TestScript")
test('Console log should have been called', () => {
     const warn = jest.spyOn(console, "warn").mockImplementation(() => {});

    someComplexFunction();
    
    expect(warn).toHaveBeenCalledWith('some important message');
    
    warn.mockRestore();
});

0
On

For me it worked only when I moved spy creation to beforeEach instead of before all.

  let logSpy: jest.Spied<typeof console.log>;

  beforeEach(() => {
    logSpy = jest.spyOn(console, 'log').mockImplementation(() => {
      // Do nothing
    });
  });

  afterEach(() => {
    logSpy.mockRestore();
  });
0
On

Have you tried this ? It works here

function helloWorld() {
  console.log("Hello, world");
}

jest.spyOn(console, "log");

it("Mock console correctly", () => {
  helloWorld();
  expect(console.log).toHaveBeenCalled();
  expect(console.log).toHaveBeenCalledWith("Hello, world");
});