简体   繁体   English

TypeScript 中导入的 object 的模拟功能

[英]Mock functions of an imported object in TypeScript

I have a TypeScript file which exports two objects (created by Typegoose ).我有一个 TypeScript 文件,它导出两个对象(由Typegoose创建)。

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

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

I import the script into the script under test.我将脚本导入到被测脚本中。

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

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

Now I tried to mock the call 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);
  });
});

But I got the following error - Number of calls: 0 .但我收到以下错误 - Number of calls: 0

How can I mock a function of an imported object?如何模拟进口 object 的 function?

You should implementate the factory function of jest.mock(moduleName, factory, options) .您应该实现jest.mock(moduleName, factory, options)的工厂 function 。

Eg例如

my-document.ts : 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 : 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 : 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);
  });
});

unit test results with 100% coverage:覆盖率 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

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

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