【问题标题】:How can I mock return value of chained function of a constructor function?如何模拟构造函数的链式函数的返回值?
【发布时间】:2021-01-11 12:30:45
【问题描述】:

我需要用 jest 模拟 csvJsonArray 的值

const csv = require('csvtojson')

const csvJsonArray = await csv().fromFile(csvFilePath)

我已经尝试了以下

jest.mock('csvtojson', () => jest.fn())
const fromFile = jest.fn().mockReturnValue(commTemplateCsvJsonArray)
csv.mockImplementation(() => ({fromFile}))

但是这里 csvJsonArray 的值为 null

如何模拟构造函数的链式函数的返回值?

【问题讨论】:

    标签: javascript node.js unit-testing jestjs mocking


    【解决方案1】:

    由于csv().fromFile() 方法的返回值是promise,您应该使用mockFn.mockResolvedValue(value) 模拟解析后的值。

    例如

    main.js:

    const csv = require('csvtojson');
    
    async function main() {
      const csvFilePath = './test.csv';
      const csvJsonArray = await csv().fromFile(csvFilePath);
      return csvJsonArray;
    }
    
    module.exports = { main };
    

    main.test.js:

    const { main } = require('./main');
    const csv = require('csvtojson');
    
    jest.mock('csvtojson');
    
    describe('65620607', () => {
      it('should pass', async () => {
        const commTemplateCsvJsonArray = [1, 2, 3];
        const fromFile = jest.fn().mockResolvedValue(commTemplateCsvJsonArray);
        csv.mockImplementation(() => ({ fromFile }));
        const actual = await main();
        expect(actual).toEqual([1, 2, 3]);
        expect(csv).toBeCalledTimes(1);
        expect(fromFile).toBeCalledWith('./test.csv');
      });
    });
    

    单元测试结果:

     PASS  examples/65620607/main.test.js
      65620607
        ✓ should pass (4 ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |     100 |      100 |     100 |     100 |                   
     main.js  |     100 |      100 |     100 |     100 |                   
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        5.705 s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 2021-10-25
      • 2014-02-13
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      相关资源
      最近更新 更多