簡體   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.

我的代碼結構:

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


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

 }

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

     return returnValueFromClassA;
 }
}

到目前為止我已經嘗試過:

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


這是我得到的錯誤:

TypeError: this._objectOfClassA.getSomething is not a function

注意:我不想在我的測試 function 中初始化 class A 的 object。 我只想模擬 class。

我還在 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.

例如:

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

const b = new B(mockA);

expect(mockA.getSomething)
    .toHaveBeenCalled();

鑒於 mockA 與 class A 的接口完全匹配,這不應產生類型錯誤。

要模擬 A 的方法的返回值,請參閱 mocking 單個函數與 Jest。

事實證明,這比試圖模擬整個模塊更簡單、更簡潔。 由於您使用 IoC 作為模式,mocking 該模塊不是必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM