网站搜索

node.js - 使用 Jest 模拟 TypeDI 服务


我正在使用带有 TypeScript、TypeDI 和 Jest 的 Node。我正在创建相互依赖的服务,比如说:

@Service()
export class MainService{
constructor(private secondService: SecondService){}
public someMethod(someString: string) // implementation depends on secondService
}

@Service()
export class SecondService{
constructor(private thirdService: ThirdService){}
}

@Service()
export class ThirdService{
constructor(){}
}

我想测试 MainService,但要实例化它,我需要传入依赖,而那个依赖又需要另一个依赖。我尝试这样做,它可以运行,但很丑:

const secondService = new SecondService(new ThirdService());
jest
    .spyOn(secondService, "someMethod")
    .mockImplementation((someString: string) => {
        // do something
        return something;
    });
const mainService = new MainService(secondService);
// use mainService in tests

当然,创建依赖的新实例并不总是一个选项,尤其当它有许多依赖时更绝对不是一个选项。

我认为它应该看起来更像:

const secondService = SomeMockFactory.create(SecondService);

但是我找不到任何在切断依赖的同时创建模拟的方法。我尝试使用

const secondService = jest.genMockFromModule("path/to/second/service");

但是在尝试 spyOn secondService 的方法后,TS 抛出了错误,提示“someMethod 不是一个函数。我遗漏了什么/做错了什么?我需要除了 Jest 外的其他库吗?

答案#1

过了一会儿,我发现了如何使用默认的 Jest 行为来做到这一点。

首先,你需要在 path/to/second/service/__mocks__ 中创建 SecondService 的模拟,如下所示:

// path/to/second/service/__mocks__/SecondService.ts
const mock = jest.fn().mockImplementation(() => ({
  async thingSecondServiceDoInFirstService(
    param: number
  ): number {
    return 1;

}));
export default mock;

SecondService 必须是默认导出,例如:

// path/to/second/service/SecondService.ts
    @Service()
export default class SecondService {
constructor(private thirdService: ThirdService) {}
  async thingSecondServiceDoInFirstService(
    param: number
  ): number {
    return this.thirdService.thingThirdServiceDoInSecond(param);
  }
}

在测试文件中,你必须在导入 SecondService 之前使用 jest.mock,然后从 mock 创建 SecondService 实例:

jest.mock("path/to/second/service/SecondService");
import SecondService from "path/to/second/service/SecondService";
import MainService from "path/to/main/service/MainService";

describe("Test main service", () => {

  const SecondServiceMock = <jest.Mock<SecondService>>SecondService;
  let secondService = new SecondServiceMock();

  beforeEach(() => {
    mainService = new MainService(secondService);
  });

// test logic...
}

如请求的那样,ThirdService 不再需要。