Skip to content

Instantly share code, notes, and snippets.

@i-like-robots
Created April 27, 2021 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save i-like-robots/5398acf6c1363908a14df0c838a3d39f to your computer and use it in GitHub Desktop.
Save i-like-robots/5398acf6c1363908a14df0c838a3d39f to your computer and use it in GitHub Desktop.
Mocking a callback with Jest
const fs = require('fs');
const glob = require('glob');
/**
* Find files
* @param {String} globPattern
* @returns {Promise<String[]>}
*/
function findFiles(globPattern) {
return new Promise((resolve, reject) => {
glob(globPattern, {}, (error, files) => {
if (error) {
reject(error);
} else {
resolve(files);
}
});
});
}
module.exports = { findFiles };
jest.mock('glob');
/** @type {jest.Mock} */
const glob = require('glob');
const subject = require('./fileUtils');
describe('lib/fileUtils', () => {
describe('.findFiles()', () => {
describe('when it finds files successfully', () => {
beforeEach(() => {
const mock = jest.fn((pattern, options, callback) =>
callback(null, ['file.txt']),
);
glob.mockImplementationOnce(mock);
});
it('resolves with the returned files', async () => {
expect(subject.findFiles('*.txt')).resolves.toEqual([
'file.txt',
]);
});
});
describe('when it fails for any reason', () => {
beforeEach(() => {
const mock = jest.fn((pattern, options, callback) =>
callback(new Error('Oh no!'), null),
);
glob.mockImplementationOnce(mock);
});
it('rejects with the returned error', async () => {
expect(subject.findFiles('*.txt')).rejects.toThrowError(
'Oh no!',
);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment