How to mock a glob call in node.js?

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

How to mock a glob call in node.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 10 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.

Related Threads:

How to call a fastapi route from node.js?
How to call an oracle stored procedure in node.js?
How to mock relative requests in vitest?
How to call a javascript function in a mustache template?
How to get a scalar value from mysql in node.js?
How to debug node.js/mocha test built with makefile?