【问题标题】:How do I mock a return value multiple times with different values in the same test?如何在同一个测试中使用不同的值多次模拟返回值?
【发布时间】:2021-05-28 22:53:55
【问题描述】:

我已经构建了一个使用node-glob 搜索文件的模块。

// fileCollector.js
const glob = require('glob');

exports.getFiles = (directory) => {
  return {
    freeMarker: glob.sync(directory + '/**/*.ftl'),
    sass: glob.sync(directory + '/**/*.scss')
  };
};

我正在尝试编写一个测试,以便我可以验证:

  1. 使用正确的参数调用了两次 Glob
  2. getFiles的返回值是正确的
// 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'
    });
  });
});

如何使用两个单独的返回值模拟 glob 的返回值两次,以便我可以测试 getFiles 的返回值?


注意:Jest mock module multiple times with different values 没有回答我的问题,因为它在单独的测试中模拟了一个不同的值。

【问题讨论】:

    标签: node.js jestjs


    【解决方案1】:

    使用mockReturnValueOnce 函数两次。例如:

    glob.sync
      .mockReturnValueOnce(['path/to/file.ftl'])
      .mockReturnValueOnce(['path/to/file.sass']);
    

    完整示例:

    // 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']
        });
      });
    });
    

    来源:Jest - Mock Return Values

    【讨论】:

    • 它对我有用!
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2015-12-02
    • 2022-01-04
    • 1970-01-01
    • 2020-08-10
    • 2020-08-26
    • 2021-08-13
    • 2017-11-16
    相关资源
    最近更新 更多