I need to mock the value of csvJsonArray using jest
const csv = require('csvtojson')
const csvJsonArray = await csv().fromFile(csvFilePath)
I have tried the following
jest.mock('csvtojson', () => jest.fn())
const fromFile = jest.fn().mockReturnValue(commTemplateCsvJsonArray)
csv.mockImplementation(() => ({fromFile}))
But here csvJsonArray value is null
How can I mock the return value for a chained function of a constructor function?
Since the return value of csv().fromFile()
method is a promise
, you should mock the resolved value using mockFn.mockResolvedValue(value) .
Eg
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');
});
});
unit test result:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.