NodeJS Jest中被测类使用的模拟类

xwbd5t1u  于 2023-02-21  发布在  Node.js
关注(0)|答案(1)|浏览(177)

我想模拟一个被测类的依赖(导入类)。一个例子:
classToTest.ts

import {MyRespository} from './myRepository'

export class ClassToTest {
    constructor() {
        this.myRepository = new MyRepository()
    }

    methodToTest() {
        ...
        this.myRepository.fetchSomeData()
        ...
    }
}

myRepository.ts

export class MyRepository {
    constructor() {}

    fetchSomeData() {
        ...
    }
}

如何使用jest模拟MyRepository,而不使用ClassToTest的依赖注入?

hc8w905p

hc8w905p1#

如果您使用constructor injection,那么您只需将mock对象传递给ClassToTest,这会更容易一些。

import { MyRepository } from "./myRepository";

export class ClassToTest {
  constructor(private myRepository: MyRepository) {}

  methodToTest() {
    this.myRepository.fetchSomeData();
  }
}

你的测试就是:

import { ClassToTest } from "./main";
import { MyRepository } from "./myRepository";

describe("my test", () => {
  let obj: ClassToTest;
  let mockRepo = {
    fetchSomeData: jest.fn(),
  } as MyRepository;

  beforeEach(() => {
    obj = new ClassToTest(mockRepo);
  });

  it("should test my method", () => {
    obj.methodToTest();
    expect(mockRepo.fetchSomeData).toBeCalledTimes(1);
  });
});

或者如果你想继续你的方法,你可以模拟你的类实现(参见这个方法的例子):

import { ClassToTest } from "./main";

const fetchSomeDataMock = jest.fn();

jest.mock("./myRepository", () => {
  return {
    MyRepository: jest.fn().mockImplementation(() => {
      return {
        fetchSomeData: fetchSomeDataMock,
      };
    }),
  };
});

describe("my test", () => {
  let obj: ClassToTest;

  beforeEach(() => {
    obj = new ClassToTest();
  });

  it("should test my method", () => {
    obj.methodToTest();
    expect(fetchSomeDataMock).toBeCalledTimes(1);
  });
});

查看更多:

相关问题