node.jsjestjs

How do I mock a return value multiple times with different values in the same test?


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:

  1. Glob was called twice with the correct arguments
  2. The return value of 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.


Solution

  • 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