Reputation: 6331
I've built a module that searches for files using node-glob.
// fileCollector.js
const glob = require('glob');
exports.getFiles = (directory) => {
return {
freeMarker: glob.sync(directory + '/**/*.ftl'),
sass: glob.sync(directory + '/**/*.scss')
};
};
I'm attempting to write a test so that I can verify that:
getFiles
is correct// fileCollector.test.js
const glob = require('glob');
const fileCollector = require('fileCollector');
jest.mock('glob');
describe('getFiles', () => {
it('should get files', () => {
const files = fileCollector.getFiles('/path/to/files');
expect(glob.sync.mock.calls).toEqual([['/path/to/files/**/*.ftl'], ['/path/to/files/**/*.scss']]);
expect(files).toEqual({
freeMarker: 'INSERT_MOCKED_VALUE_FROM_GLOB',
sass: 'INSERT_MOCKED_VALUE_FROM_GLOB'
});
});
});
How do I mock the return value of glob twice with two separate return values so that I can test the return value of getFiles
?
Note: Jest mock module multiple times with different values does not answer my question because it mocks a different value once in separate tests.
Upvotes: 23
Views: 35153
Reputation: 6331
Use the mockReturnValueOnce
function twice. For example:
glob.sync
.mockReturnValueOnce(['path/to/file.ftl'])
.mockReturnValueOnce(['path/to/file.sass']);
Full example:
// fileCollector.test.js
const glob = require('glob');
const fileCollector = require('fileCollector');
jest.mock('glob');
describe('getFiles', () => {
it('should get files', () => {
glob.sync
.mockReturnValueOnce(['path/to/file.ftl'])
.mockReturnValueOnce(['path/to/file.sass']);
const files = fileCollector.getFiles('/path/to/files');
expect(glob.sync.mock.calls).toEqual([['/path/to/files/**/*.ftl'], ['/path/to/files/**/*.scss']]);
expect(files).toEqual({
freeMarker: ['path/to/file.ftl'],
sass: ['path/to/file.sass']
});
});
});
Source: Jest - Mock Return Values
Upvotes: 47