上下文:我有依赖于类 A 的类 B。我想测试类 B 的方法,该方法在内部调用类 A 的方法。现在,我想通过模拟类 A 对类 B 的方法进行单元测试。
Note 1: A 类有一些私有成员
Note 2: A类没有接口
这是我的代码结构:
class Base {
someMethod() {
return "Hello ";
}
}
class A {
private _baseClassImpl: Base;
constructor(baseClassImpl: Base) {
this._baseClassImpl = baseClassImpl;
}
getSomething() {
return this._baseClassImpl.someMethod() + " Something";
}
}
class B {
constructor(objectOfClassA: A) {
this._objectOfClassA = objectOfClassA;
}
functionOfClassBToTest() {
const returnValueFromClassA = this._objectOfClassA.getSomething();
return returnValueFromClassA;
}
}
到目前为止我已经尝试过:
听取建议后我之前的帖子 https://stackoverflow.com/questions/70635377/jest-typescript-mock-class-dependencies-in-jest-and-typescript我尝试编写这样的测试:
const getSomethingMock = jest.fn().mockImplementation(() => {
return "Mock value";
});
const mockA = jest.Mocked<A> = {
getSomething: getSomethingMock
};
test("test functionOfClassBToTest", () => {
const classBToTest = new B(mockA);
expect(classBToTest.functionofClassBToTest.toStrictEqual("Hello Something");
});
上面的代码给了我这个错误:
Type '{ getSomething: jest.Mock<any, any>; }' is not assignable is not assignable to type 'Mocked<A>'.
Type '{ getSomething: jest.Mock<any, any>; }' is missing the following properties from type 'A': _baseClassImpl
当我尝试为 _baseClassImpl 提供模拟值时,如下所示:
const baseClassMock = jest.Mocked<Base> = {
someMethod: jest.fn()
};
const getSomethingMock = jest.fn().mockImplementation(() => {
return "Mock value";
});
const mockA = jest.Mocked<A> = {
getSomething: getSomethingMock,
_baseClassImpl: baseClassMock
};
打字稿给了我这个错误:
Type '{ getSomething: jest.Mock<any, any>; _baseClassImpl: jest.Mocked<Base>; }' is not assignable is not assignable to type 'Mocked<A>'.
Type '{ getSomething: jest.Mock<any, any>; _baseClassImpl: jest.Mocked<Base>; }' is not assignable is not assignable to type 'A'.
Property '_baseClassImpl' is private in type 'A' but not in type '{ getSomething: jest.Mock<any, any>; _baseClassImpl: jest.Mocked<Base>; }'
我已经尝试过我的答案以前的SO帖子 https://stackoverflow.com/questions/70635377/jest-typescript-mock-class-dependencies-in-jest-and-typescript但在与私人成员一起上课的情况下它不起作用。
一些注意事项:
Note 1: A 类包含私有成员
Note 2: A类没有接口
Note 3: 我不想在我的测试函数中初始化 A 类的对象。我只想嘲笑班级。