上下文:我有依赖于类 A 的类 B。我想测试类 B 的方法,该方法在内部调用类 A 的方法。现在,我想通过模拟类 A 来对我的类 B 的方法进行单元测试。
注1:A类有一些私有成员
注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;
}
}
到目前为止我尝试过的:
在采纳了我之前的SO帖子的建议后,我尝试编写这样的测试:
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帖子中尝试过答案,但在与私人成员一起上课的情况下它不起作用。
一些注意事项:
注1:A类包含私有成员
注2:A类没有接口
注3:我不想在我的测试函数中初始化A类的对象。我只想嘲笑班级。
通过一些尝试和这个github repo的帮助,我能够解决这个问题。
以下是参考代码:
测试 functionOfClassBToTest :
//Note: this can be also written as : const mockA = new (<any>A)() as jest.Mocked<A>;
const mockA = new (<new () => A>A)() as jest.Mocked<A>;
mockA.getSomething = jest.fn();
test("test functionOfClassBToTest", () => {
mockA.getSomething.mockReturnValueOnce("Hello Something");
const classBToTest = new B(mockA);
expect(classBToTest.functionofClassBToTest.toStrictEqual("Hello Something");
});