Should I mock module?

I’m writing tests for a piece of code using Jest. I’m testing a module called Inquirer, a CLI tool to interact with the user and mainly in this case to store values from the user (project is a text based adventure game).

Could anyone explain to me if I need to or why I should mock the library itself with jest.mock()? It does not affect the test’s outcome or even the time taken to complete the tests.

const inquirer = require('inquirer')
jest.mock('inquirer')

 test('user input with bob', async () => {
        expect.assertions(1)
        inquirer.prompt = jest.fn().mockResolvedValue({ userInput: 'bob' })
        
        await expect(name()).resolves.toEqual('bob')
    })

>Solution :

When you do jest.mock('inquirer'), jest will mock all the methods of inquirer.

So now inquirer.prompt is already a mock function.

So, you don’t need to assign another mock function to it. Within the test, you can do something like this:

inquirer.prompt.mockResolvedValue({ userInput: 'bob' });

Leave a Reply