【问题标题】:Mock class used by class under test in JestJest 中被测类使用的模拟类
【发布时间】:2023-02-21 19:49:15
【问题描述】:

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

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() {
        ...
    }
}

如何在不对 ClassToTest 使用依赖注入的情况下使用 jest 来模拟 MyRepository

【问题讨论】:

    标签: node.js jestjs ts-jest


    【解决方案1】:

    如果你使用constructor injection会更容易,所以你只需将你的模拟对象传递给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);
      });
    });
    

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

    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);
      });
    });
    

    查看更多:

    【讨论】:

    • 谢谢!第二种方法看起来非常好!但是,我不清楚的一件事是你应该向jest.mock(path, ...)提供什么路径应该是从测试文件到myRepository.ts的相对路径还是classToTest.tsmyRepository.ts之间的相对路径?
    猜你喜欢
    • 2019-09-14
    • 2018-05-04
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多