Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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')
    })

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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' });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading