简体   繁体   English

Jest/Typescript:在 Jest 和 Typescript 中模拟 class 依赖项

[英]Jest/Typescript: Mock class dependencies in Jest and Typescript

I have class B which is dependent on class A. I want to test a method of class B which is internally calling a method of class A. Now, I want to unit test my method of class B by mocking class A. I have class B which is dependent on class A. I want to test a method of class B which is internally calling a method of class A. Now, I want to unit test my method of class B by mocking class A.

My code structure:我的代码结构:

class A {
  getSomething() {
     return "Something";
  }
}


class B {
  constructor(objectOfClassA: A) {
      this._objectOfClassA = objectOfClassA;

 }

 functionofClassBToTest() {
     const returnValueFromClassA = this.__objectOfClassA.getSomething();

     return returnValueFromClassA;
 }
}

What I have tried so far:到目前为止我已经尝试过:

import ....
import { mocked } from 'jest-mock';

jest.mock("./A", () => {
    return {
        A: jest.fn().mockImplementation(() => {
            return {
                getSomething: getSomethingMock
            }
        })
    };
});

const getSomethingMock = jest.fn().mockImplementation(() => {
    return "Mock value";
});

const mockA = mocked(A, true);

test("test functionofClassBToTest", () => {
    const classBToTest = new B(mockA);

    expect(classBToTest.functionofClassBToTest.toStrictEqual("Mock value");
});


This is the error that I am getting:这是我得到的错误:

TypeError: this._objectOfClassA.getSomething is not a function

Note: I don't want to initialize an object of class A inside my test function.注意:我不想在我的测试 function 中初始化 class A 的 object。 I only want to mock the class.我只想模拟 class。

I also found some previous posts on SO: Post1 and Post2 but nothing worked.我还在 SO: Post1Post2上找到了一些以前的帖子,但没有任何效果。

Given that Typescript is structurally typed , it should be possible to simply construct an object literally that matches the interface of the A class and pass that into class B. Given that Typescript is structurally typed , it should be possible to simply construct an object literally that matches the interface of the A class and pass that into class B.

For example:例如:

const mockA = {
  getSomething: jest.fn()
};

const b = new B(mockA);

expect(mockA.getSomething)
    .toHaveBeenCalled();

This should not generate type errors given mockA exactly matches the interface of class A.鉴于 mockA 与 class A 的接口完全匹配,这不应产生类型错误。

To mock the return value of A's methods, refer to mocking individual functions with Jest.要模拟 A 的方法的返回值,请参阅 mocking 单个函数与 Jest。

This proves to be simpler and more succinct than attempting to mock the entire module.事实证明,这比试图模拟整个模块更简单、更简洁。 Since you've used IoC as a pattern, mocking the module is not necessary.由于您使用 IoC 作为模式,mocking 该模块不是必需的。

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

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