How to Mock the glob NPM Package Using Jest (2025 Guide)

As a senior developer, you've probably worked with the glob package to perform file pattern matching in Node.js. But what happens when you need to mock glob in your Jest tests?

Whether you're testing CLI tools, build systems, or file-based utilities, mocking glob ensures your tests are fast, reliable, and don’t depend on the file system.

In this guide, you'll learn exactly how to mock the glob library using Jest in a clean and maintainable way.


✅ Why Mock glob?

  • Avoid file system dependencies in tests
  • Control test input and output
  • Simulate various file-matching scenarios (no files, multiple files, invalid patterns)

🛠️ Setup: A Sample Function Using glob

Let’s say we have a utility that finds .js files in a directory:

// fileScanner.js
const glob = require('glob');

function findJSFiles(dirPath) {
  return new Promise((resolve, reject) => {
    glob(`${dirPath}/**/*.js`, (err, files) => {
      if (err) return reject(err);
      resolve(files);
    });
  });
}

module.exports = { findJSFiles };

🧪 How to Mock glob in Jest

Step 1: Use jest.mock

In your test file, use jest.mock('glob') to intercept the actual call:

// fileScanner.test.js
const glob = require('glob');
const { findJSFiles } = require('./fileScanner');

jest.mock('glob');

describe('findJSFiles', () => {
  it('returns matched JS files', async () => {
    glob.mockImplementation((pattern, callback) => {
      callback(null, ['src/index.js', 'src/utils/helper.js']);
    });

    const result = await findJSFiles('src');
    expect(result).toEqual(['src/index.js', 'src/utils/helper.js']);
  });

  it('handles glob errors gracefully', async () => {
    glob.mockImplementation((pattern, callback) => {
      callback(new Error('Something went wrong'), null);
    });

    await expect(findJSFiles('src')).rejects.toThrow('Something went wrong');
  });
});

✅ Best Practices

  • Mock only what you need – avoid over-mocking
  • Restore mocks using jest.resetAllMocks() if needed
  • Use mockResolvedValue / mockRejectedValue if wrapping with promisify

📦 Bonus: Mocking glob.sync

If your code uses glob.sync, you can mock it like this:

glob.sync = jest.fn(() => ['file1.js', 'file2.js']);

Or if you're using ES Modules with import glob from 'glob', the mocking will look slightly different. You’d use jest.mock() with a manual mock or vi.mock() if using Vitest.


📈 SEO Keywords Targeted

  • How to mock glob in Jest
  • Jest mock npm package example
  • Mocking glob in Node.js tests
  • Unit testing with Jest and glob
  • Jest mock filesystem pattern matching

🧩 Conclusion

Mocking glob in Jest is straightforward and powerful. It allows you to write deterministic and reliable unit tests without depending on actual file structures.

As a senior developer, knowing how to effectively mock third-party libraries like glob helps you ship code that’s both well-tested and maintainable.