🧪 How to Mock mkdirp in Jest Like a Senior Developer

When writing unit tests in Node.js, especially with filesystem-related libraries like mkdirp, you want to avoid touching the real file system. That’s where mocking comes in. In this quick guide, we'll walk through how to mock mkdirp using Jest so your tests stay fast, safe, and isolated.


🔧 What is mkdirp?

mkdirp is a handy Node.js utility that makes it easy to create nested directories recursively—similar to mkdir -p in Unix.

Example usage:

const mkdirp = require('mkdirp');

mkdirp('/tmp/foo/bar/baz')
  .then(made => console.log(`Made directories: ${made}`));

But what if you don’t want to actually create directories in your tests?


🎯 Why Mock mkdirp in Tests?

Mocking mkdirp ensures:

  • No actual file system changes.
  • Faster test runs.
  • Better isolation for unit tests.
  • Easier simulation of edge cases (e.g., permission errors).

🧪 How to Mock mkdirp in Jest

Here’s how to mock mkdirp in your Jest test suite.

1. Install mkdirp and jest (if you haven’t already):

npm install mkdirp
npm install --save-dev jest

2. Code Under Test: directoryService.js

Let’s say you have a module like this:

// directoryService.js
const mkdirp = require('mkdirp');

async function createOutputDir(path) {
  try {
    const made = await mkdirp(path);
    return made;
  } catch (err) {
    throw new Error(`Failed to create directory: ${err.message}`);
  }
}

module.exports = { createOutputDir };

3. Mocking in Your Test: directoryService.test.js

// directoryService.test.js
const mkdirp = require('mkdirp');
const { createOutputDir } = require('./directoryService');

jest.mock('mkdirp'); // Auto-mocks all exported functions

describe('createOutputDir', () => {
  it('should call mkdirp with the correct path', async () => {
    mkdirp.mockResolvedValue('/tmp/test/path');

    const result = await createOutputDir('/tmp/test/path');

    expect(mkdirp).toHaveBeenCalledWith('/tmp/test/path');
    expect(result).toBe('/tmp/test/path');
  });

  it('should throw an error if mkdirp fails', async () => {
    mkdirp.mockRejectedValue(new Error('Disk is full'));

    await expect(createOutputDir('/fail/path')).rejects.toThrow('Failed to create directory: Disk is full');
  });
});

🧠 Pro Tips

  • Always test both success and failure scenarios.
  • Use mockResolvedValue() and mockRejectedValue() for mocking async behavior.
  • You can also use jest.fn() if you want more fine-grained control.

🏁 Conclusion

Mocking third-party libraries like mkdirp with Jest is a crucial skill for any serious Node.js developer. By mocking filesystem operations, you can focus on logic, avoid flaky tests, and simulate any scenario without side effects.

Now go ahead and test like a pro. And remember: real devs don’t let mkdirp touch the disk in unit tests. 😉