我想用Jest对TS代码进行单元测试:
MyClass.ts
import Dependency from "./Dependency";
export default class MyClass {
public constructor(private dependency: Dependency) {}
public DoIt(): string {
return this.dependency.MyProp;
}
}
它使用这个类:
export default class Dependency {
public get MyProp(): string {
return "A string";
}
}
这是我迄今为止的测试:
import MyClass from "./MyClass";
import Dependency from "./Dependency";
jest.mock("./Dependency"); // Here we do auto mocking
it("connects with the server for match info messages", () => {
// Arrange
const dependency = new Dependency();
const sut = new MyClass(dependency);
// dependency.MyProp = "Another string"; // Cannot assign to 'MyProp' because it is a read-only property.ts(2540)
jest.spyOn(dependency, "MyProp", "get").mockReturnValueOnce("Another string"); // Error: MyProp property does not exist
// Act
const retval = sut.DoIt();
// Assert
expect(retval).toStrictEqual("Another string");
});
正如评论中所指出的,我无法正确地模拟MyProp
属性。在运行时,它是undefined
,因为auto-mocking不把它看作一个函数,所以它忽略了它
问题:如何在不放弃自动模拟的情况下正确模拟模拟上的公共属性?
不要用自动模拟版本模拟./Dependency
模块。只需删除jest.mock()
语句,它就会起作用。我们只需要使用jest.spyOn()
模拟MyProp
getter方法。
import MyClass from "./MyClass";
import Dependency from "./Dependency";
it("connects with the server for match info messages", () => {
// Arrange
const dependency = new Dependency();
const sut = new MyClass(dependency);
jest.spyOn(dependency, "MyProp", "get").mockReturnValueOnce("Another string"); // Error: MyProp property does not exist
// Act
const retval = sut.DoIt();
// Assert
expect(retval).toStrictEqual("Another string");
});