How to mock a glob call in node.js?

by giovanny.lueilwitz , in category: Javascript , 6 months ago

How to mock a glob call in node.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 6 months ago

@giovanny.lueilwitz 

You can mock a glob call in Node.js using a mocking library such as Jest. Here’s an example of how you can mock a glob call using Jest:

  1. Install Jest if you haven’t already:
1
npm install jest --save-dev


  1. Create a function that calls glob and exports it:
1
2
3
4
5
6
7
8
// file.js
const glob = require('glob');

function getFiles() {
  return glob.sync('path/to/files/*.txt');
}

module.exports = getFiles;


  1. Create a test file where you mock the glob call using Jest:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// file.test.js
jest.mock('glob', () => ({
  sync: jest.fn(() => ['file1.txt', 'file2.txt']),
}));

const getFiles = require('./file');

test('getFiles returns array of files', () => {
  const files = getFiles();
  expect(files).toEqual(['file1.txt', 'file2.txt']);
});


  1. Run the test using Jest:
1
npm test


This will mock the glob.sync method in your test file and return the files you specify, allowing you to test the behavior of your function without actually calling glob.