typescript Jest:如何模拟esModule的方法?

kxe2p93d  于 2022-11-26  发布在  TypeScript
关注(0)|答案(2)|浏览(189)

我有一个简单的函数,使用库jszip压缩一些文件夹和文件:

// app.ts
const runJszip = async (): Promise<void> => {
  const zip = new Jszip();

  zip.folder('folder')?.file('file.txt', 'just some text');
  zip.file('file.txt', 'just some text');

  await zip.generateAsync({ type: 'blob' });
};

我想通过监视方法folderfile来测试它。为此,我使用了模拟部分策略来处理此库的默认导出:

// app.test.ts
import { runJszip } from './app';

const mockFile = jest.fn();
const mockFolder = jest.fn();

const mockJszip = jest.fn().mockImplementation(() => {
  return {
    folder: mockFolder,
    file: mockFile,
  };
});

jest.mock('jszip', () => {
  return jest.fn().mockImplementation(() => ({
    __esModule: true,
    default: mockJszip,
  }));
});

test('jszip', async () => {
  await runJszip();

  expect(mockFile).toHaveBeenCalledTimes(2);
  expect(mockFolder).toHaveBeenCalledTimes(1);
});

不幸的是,我似乎无法正确模拟folder方法,如以下错误消息所示:

Message:
      zip.folder is not a function

      4 |   const zip = new Jszip();
      5 |
    > 6 |   zip.folder('folder')?.file('file.txt', 'just some text');

那么,有人知道我如何嘲笑和监视这种方法吗?
看一看minimal reproducible example

qzwqbdag

qzwqbdag1#

我让mockFolder在@bln的响应中返回一个模拟的Jszip示例,使它按预期工作:

import { runJszip } from './app';

const mockFile = jest.fn();
let mockFolder: jest.Mock;

function mockJszip() {
  mockFolder = mockFolder ?? jest.fn(mockJszip);
  return {
    folder: mockFolder,
    file: mockFile,
    generateAsync: jest.fn(),
  };
}

jest.mock('jszip', () => {
  return {
    __esModule: true,
    default: mockJszip,
  };
});

test('jszip', async () => {
  await runJszip();

  expect(mockFile).toHaveBeenCalledTimes(2);
  expect(mockFolder).toHaveBeenCalledTimes(1);
});

https://stackblitz.com/edit/webpack-5-react-starter-ofxcmy?file=src/app.test.ts

bvuwiixz

bvuwiixz2#

import { runJszip } from './app';

const mockFile = jest.fn();
const mockFolder = jest.fn();

function mockJszip() {
  return {
    folder: mockFolder,
    file: mockFile,
    generateAsync: jest.fn(),
  };
}

jest.mock('jszip', () => {
  return {
    __esModule: true,
    default: mockJszip,
  };
});

test('jszip', async () => {
  await runJszip();

  expect(mockFile).toHaveBeenCalledTimes(2);
  expect(mockFolder).toHaveBeenCalledTimes(1);
});

对于?.file()链接,可能在mockJszip周围有一些mockImplementation

相关问题