🔍 How to Mock the inquirer
NPM Package in Jest (The Right Way)
When writing tests for a Node.js CLI app, chances are you’re using inquirer
for interactive prompts. But when it comes to unit testing, you don’t want your tests waiting for manual input. That’s where mocking inquirer
with Jest comes in.
In this quick guide, we’ll show you how to mock inquirer
with Jest like a pro—no hacks, no headaches.
📦 What is inquirer
?
inquirer
is a popular Node.js library used to build command-line interfaces with interactive prompts. It’s widely adopted for tools, generators, and CLI wizards.
npm install inquirer
Example usage:
const inquirer = require('inquirer');
async function askUser() {
const answers = await inquirer.prompt([
{ type: 'input', name: 'username', message: 'Enter your name:' },
]);
console.log(`Hello, ${answers.username}!`);
}
Cool, right? But now let’s make it testable.
🎯 The Goal: Mock inquirer.prompt()
in Jest
We want to replace inquirer.prompt()
with a mock function that returns predefined answers.
🧪 Step-by-Step: Mocking inquirer
with Jest
1. Project Setup
Make sure jest
is installed:
npm install --save-dev jest
In your package.json
, define:
"scripts": {
"test": "jest"
}
2. Example CLI Code (askUser.js
)
const inquirer = require('inquirer');
async function askUser() {
const answers = await inquirer.prompt([
{ type: 'input', name: 'username', message: 'Enter your name:' },
]);
return `Hello, ${answers.username}!`;
}
module.exports = { askUser };
3. Writing the Jest Test (askUser.test.js
)
jest.mock('inquirer');
const inquirer = require('inquirer');
const { askUser } = require('./askUser');
describe('askUser', () => {
it('should return greeting with mocked username', async () => {
inquirer.prompt.mockResolvedValue({ username: 'TestUser' });
const result = await askUser();
expect(result).toBe('Hello, TestUser!');
});
});
🧠 Pro Tip: Avoid Real Prompts in CI/CD
Mocking inquirer
is essential if you're running tests in CI/CD pipelines. Nothing ruins a build like a prompt waiting for input!
🚫 Common Mistake: Forgetting mockResolvedValue
inquirer.prompt()
returns a Promise. If you use mockReturnValue
, it won’t work correctly. Always use mockResolvedValue
for async mocks.
✅ Correct:
inquirer.prompt.mockResolvedValue({ username: 'Jane' });
❌ Incorrect:
inquirer.prompt.mockReturnValue({ username: 'Jane' }); // Won’t await!
🧼 Clean Mocks After Each Test (Optional)
If your test suite is large:
afterEach(() => {
jest.clearAllMocks();
});
📚 TL;DR
Step | Action |
---|---|
1️⃣ | Install jest and inquirer |
2️⃣ | Use jest.mock('inquirer') |
3️⃣ | Mock inquirer.prompt with mockResolvedValue |
4️⃣ | Write your test logic and assert |
🔚 Final Thoughts
Mocking inquirer
in Jest is simple, powerful, and essential for test automation. As a senior developer, you don’t want flaky tests—or worse, manual prompts slowing things down.
By mocking properly, you keep your test suite fast, reliable, and CI-friendly.