我对jest和mocking非常陌生,我有一个fs模块读取流,它有2个事件和数据,我试着模仿下面的代码
ReadFile.js
const csv = require('csv-parser'); let storeData=[]; csvFileReader() { fs.createReadStream(path.resolve(__dirname, "./abc.csv")) .pipe(csv()) .on('data', async (row) => { storeData[0] = row.postcode; .on('end', () => { console.log('Done') }
ReadFileTest.js
import ReadFile from './readFile.js'; const fs = require('fs'); jest.mock('fs'); describe('Load File', () => { const readFile= new ReadFile(); test('Test data handler', async () => { const mockPipeOn = { on: jest.fn().mockImplementation(function(this, event, handler) { if (event === 'data') { jest.fn.mockReturnValueOnce("Reading Data") if (event === 'end') { jest.fn.mockReturnValueOnce("Completed Reading Data") return this; }), }; const mockReadStream = { pipe: jest.fn().mockReturnValueOnce(mockPipeOn) }; const createReadStream = jest.fn().mockReturnValueOnce(mockReadStream); await readFile.csvFileReader(); });
我在'this‘关键字上遇到错误它没有进入'data’和'end‘错误处理程序
上云精选
2核2G云服务器 每月9.33元起,个人开发者专属3年机 低至2.3折
您应该使用 mockFn.mockReturnThis() 来返回上下文。
例如。
import fs from 'fs'; import path from 'path'; import csv from 'csv-parser'; class ReadFile { csvFileReader() { fs.createReadStream(path.resolve(__dirname, './abc.csv')) .pipe(csv()) .on('data', async (row) => { console.log('Storing Data'); .on('end', () => { console.log('Done'); export default ReadFile;
ReadFile.test.js
import ReadFile from './ReadFile'; import fs from 'fs'; jest.mock('fs'); describe('67216891', () => { const readFile = new ReadFile(); it('should store', () => { const mReadStream = { pipe: jest.fn().mockReturnThis(), on: jest.fn().mockImplementation(function (event, handler) { handler(); return this; fs.createReadStream.mockReturnValueOnce(mReadStream); readFile.csvFileReader(); expect(fs.createReadStream).toBeCalledTimes(1); expect(mReadStream.pipe).toBeCalledTimes(1); expect(mReadStream.on).toBeCalledWith('data', expect.any(Function)); expect(mReadStream.on).toBeCalledWith('end', expect.any(Function)); });
测试结果:
PASS examples/67216891/ReadFile.test.js (8.891 s) 67216891 ✓ should store (20 ms) console.log Storing Data at ReadFile.<anonymous> (examples/67216891/ReadFile.js:10:17) console.log at examples/67216891/ReadFile.js:13:17 -------------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s -------------|---------|----------|---------|---------|------------------- All files | 100 | 100 | 100 | 100 |