Created
April 27, 2021 10:23
-
-
Save i-like-robots/5398acf6c1363908a14df0c838a3d39f to your computer and use it in GitHub Desktop.
Mocking a callback with Jest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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