如何在Jest测试中模仿工人?

2cmtqfgy  于 2022-12-08  发布在  Jest
关注(0)|答案(2)|浏览(121)

我有一个考验:

import { convertHeicToPng } from './heicUtils';

class Worker {
  url: string;
  onmessage: (m?: any) => void;
  constructor(stringUrl: string) {
    this.url = stringUrl;
    this.onmessage = () => {};
  }

  postMessage(msg: any) {
    this.onmessage(msg);
  }
}

(window.Worker as any) = Worker;

describe('test heicUtils', () => {
  test('should convert HEIC to PNG', async () => {
    const file = new File([''], 'test.heic', { type: 'image/heic' });
    const base64 = await convertHeicToPng(file);
    expect(base64).toContain('data:image/png;base64');
  });
});

heicUtils中,我使用heic2any,它使用WebWorkers。

f3temu5u

f3temu5u1#

由于您正在测试heicUtils模块,因此您应该模拟heic2any库,否则,您将测试第三方库而不是您自己的代码。
在模拟中,您应该定义heicUtils使用的heic2any的函数/方法,以及它们应该为您打算编写的每个测试用例返回什么。
如何模拟模块的示例可在此处找到:https://jestjs.io/docs/manual-mocks

oyjwcjzk

oyjwcjzk2#

tsc && mocha --报告程序规范-t 5000 --退出
.npm安装摩卡
.然后执行以下命令。示例my github:https://github.com/www778878net/koa78-base78

相关问题