![](/img/trans.png)
[英]How can I spy on a function and return a mock value from inside another function using jasmine?
[英]How can I mock return value of chained function of a constructor function?
我需要使用 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
如何模拟构造函数 function 的链式 function 的返回值?
由于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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.