有模拟 FS 文件流

Jest Mock FS File Stream

我对开玩笑和嘲笑很陌生,我有一个 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' 错误处理程序

您应该使用 mockFn.mockReturnThis() 来 return 上下文。

例如

ReadFile.js:

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
    Done

      at examples/67216891/ReadFile.js:13:17

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |      100 |     100 |     100 |                   
 ReadFile.js |     100 |      100 |     100 |     100 |                   
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.159 s