繁体   English   中英

如何使用玩笑模拟 FileReader

[英]How to mock FileReader using jest

我需要使用玩笑来模拟使用FileReader的 function。 特别是 function readAsBinaryStringonload

我创建了一些代码:

FileReader.readAsBinaryString = () => mock.mockReturnValue(null);

但它不起作用。 如何使用 jest 模拟FileReader和您的函数?

Function 进行测试:

handleFileUpload(event) {
  let reader = new FileReader();
  let file = event.target.files[0];

  reader.readAsBinaryString(file);

  reader.onload = () => {
    let base64String = btoa(reader.result);
    this.object.image = 
  };
},

您可以使用jest.spyOn(object, methodName, accessType?)来监视FileReaderreadAsBinaryString方法。 readAsBinaryString是一个实例方法,而不是FileReader构造函数的 static 方法。 此外, readAsBinaryString的返回值为void 所以你不能模拟一个返回值。

例如

index.ts

export function main() {
  const fr = new FileReader();
  const blob = new Blob();
  fr.readAsBinaryString(blob);
}

index.spec.ts ,我们需要监视FileReader.prototype.readAsBinaryString ,因为它是一个实例方法。

import { main } from './';

describe('main', () => {
  test('should mock FileReader', () => {
    const readAsBinaryStringSpy = jest.spyOn(FileReader.prototype, 'readAsBinaryString');
    main();
    expect(readAsBinaryStringSpy).toBeCalledWith(new Blob());
  });
});

覆盖率 100% 的单元测试结果:

PASS  src/stackoverflow/58644737/index.spec.ts
  main
    ✓ should mock FileReader (10ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.852s, estimated 9s

更新

index.ts

export class Component {
  object = {
    image: ''
  };
  handleFileUpload(event) {
    let reader = new FileReader();
    let file = event.target.files[0];

    reader.readAsBinaryString(file);

    reader.onload = () => {
      let base64String = btoa(reader.result as string);
      this.object.image = base64String;
    };

    return reader;
  }
}

index.spec.ts

import { Component } from './';

const cmp = new Component();

describe('main', () => {
  beforeEach(() => {
    jest.restoreAllMocks();
  });
  test('should test handle file upload correctly', () => {
    const mFile = new File(['go'], 'go.pdf');
    const mEvent = { target: { files: [mFile] } };
    const readAsBinaryStringSpy = jest.spyOn(FileReader.prototype, 'readAsBinaryString');
    const btoaSpy = jest.spyOn(window, 'btoa');
    const reader = cmp.handleFileUpload(mEvent);
    expect(reader).toBeInstanceOf(FileReader);
    if (reader.onload) {
      Object.defineProperty(reader, 'result', { value: 'gogo' });
      const mOnloadEvent = {} as any;
      reader.onload(mOnloadEvent);
      expect(btoaSpy).toBeCalledWith('gogo');
      expect(cmp.object.image).toBe(btoa('gogo'));
    }
    expect(readAsBinaryStringSpy).toBeCalledWith(mFile);
  });
});

覆盖率 100% 的单元测试结果:

 PASS  src/stackoverflow/58644737/index.spec.ts (7.328s)
  main
    ✓ should test handle file upload correctly (13ms)

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

源码: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58644737

我已经取得了一些进展:

const dummy = {
     readAsBinaryString: jest.fn(),
        onload: function(){
          wrapper.vm.object.image = '...'
        }
     }
   }

window.FileReader = jest.fn(() => dummy)

问题是 onload 在实际调用时不会被嘲笑:

reader.onload = function() {
}

只有当我打电话

reader.onload()

所以我认为对 dummy 的 onload 声明是错误的。

我个人无法在我的 Vue-test-utils 设置jest.spyOn(FileReader.prototype, 'readAsDataURL'); 不断产生以下错误: Cannot spy the readAsDataURL property because it is not a function; undefined given instead Cannot spy the readAsDataURL property because it is not a function; undefined given instead

如果它可以帮助其他有此问题的人,我设法使用以下方法成功地模拟了 FileReader 原型:

Object.defineProperty(global, 'FileReader', {
  writable: true,
  value: jest.fn().mockImplementation(() => ({
    readAsDataURL: jest.fn(),
    onLoad: jest.fn()
  })),
})

然后在我的测试中,我能够通过 mocking 事件测试文件输入 onChange 方法(使用 FileReader)并像这样手动触发它:

const file = {
  size: 1000,
  type: "audio/mp3",
  name: "my-file.mp3"
}
const event = {
  target: {
    files: [file]
  }
}
wrapper.vm.onChange(event)

很晚的评论,但就其价值而言,这就是我能够模拟 FileReader 的方式:

首先,我创建了一个返回 new FileReader() 而不是直接调用它的 function。

export function fileReaderWrapper() {
  return new FileReader();
}

那么需要文件阅读器的代码可以调用那个function

const reader = fileReaderWrapper();
reader.readAsDataURL(file);
while (reader.readyState !== 2) {
  yield delay(100);
}
const imageData = reader.result;

现在我的测试可以使用 jest 来模拟我检查的所有内容。我不再需要在测试中使用超时来等待 FileReader 完成读取文件。

jest.mock('~/utils/helper', () => ({
  fileReaderWrapper: jest.fn().mockReturnValue({
    readAsDataURL: (file: File) => {
      return;
    },
    readyState: 2,
    result: 'data:image/png;base64,undefined',
  }),
}));

如果你想调用 onload 事件作为 readAsText 的一部分你可以使用下面的代码

const readAsTextMock = jest.fn();
jest.spyOn(global, 'FileReader').mockImplementation(function () {
  const self = this;
  this.readAsText = readAsTextMock.mockImplementation(() => {
    self.onload({ target: { result: "file read result mock" } });
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM