【问题标题】:Mock functions of an imported object in TypeScriptTypeScript 中导入对象的模拟函数
【发布时间】:2023-03-26 01:03:02
【问题描述】:

我有一个 TypeScript 文件,它导出两个对象(由 Typegoose 创建)。

// my-document.ts
export class MyDocument extends Typegoose {
  // ...
}

export const MyDocumentModel = new MyDocument().getModelForClass(MyDocument, ...)

我将脚本导入到被测脚本中。

// script-under-test.ts
import { MyDocumentModel } from './my-document';

export async function createDocument(doc: any) {
  return await MyDocumentModel.create(doc);
}

现在我尝试模拟调用 MyDocumentModel.create(doc)

// script-under-test.test.ts
import { MyDocumentModel } from './my-document';
import { createDocument } from './script-under-test.ts';

jest.mock('./my-document');

describe('creation', () => {
  const MyDocumentModelMock = MyDocumentModel as unknown as jest.Mock;

  it('should create a new document', async () => {
    const payload = { foo: 'bar' };
    const document = {} as Document;
    const createMock = jest.fn();
    createMock.mockReturnValueOnce(document);
    MyDocumentModel.mockImplementation(() => ({ create: createMock }));

    const result = await createDocument(payload);

    expect(createMock).toHaveBeenCalledWith(payload);
    expect(result).toStrictEqual(document);
  });
});

但我收到以下错误 - Number of calls: 0

如何模拟导入对象的函数?

【问题讨论】:

  • 好像可以写MyDocumentModel.create = createMock

标签: typescript unit-testing mocking jestjs typegoose


【解决方案1】:

你应该实现jest.mock(moduleName, factory, options)的工厂函数。

例如

my-document.ts:

// simulate the Typegoose class
class Typegoose {
  public getModelForClass(cls) {
    return cls.toString();
  }
}

export class MyDocument extends Typegoose {}

export const MyDocumentModel = new MyDocument().getModelForClass(MyDocument);

script-under-test.ts:

import { MyDocumentModel } from './my-document';

export async function createDocument(doc: any) {
  return await MyDocumentModel.create(doc);
}

script-under-test.test.ts:

import { MyDocumentModel } from './my-document';
import { createDocument } from './script-under-test';

jest.mock('./my-document', () => {
  const mMyDocumentModel = { create: jest.fn() };
  return { MyDocumentModel: mMyDocumentModel };
});

describe('creation', () => {
  it('should create a new document', async () => {
    const payload = { foo: 'bar' };
    MyDocumentModel.create.mockResolvedValueOnce(document);
    const result = await createDocument(payload);
    expect(MyDocumentModel.create).toHaveBeenCalledWith(payload);
    expect(result).toStrictEqual(document);
  });
});

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

 PASS  stackoverflow/61388982/ script-under-test.test.ts (10.103s)
  creation
    ✓ should create a new document (5ms)

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

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多