I want to unit test this TS code with Jest:
MyClass.ts
import Dependency from "./Dependency";
export default class MyClass {
public constructor(private dependency: Dependency) {}
public DoIt(): string {
return this.dependency.MyProp;
}
}
It uses this class:
export default class Dependency {
public get MyProp(): string {
return "A string";
}
}
This is my test so far:
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");
});
As noted in the comments, I can’t properly mock the MyProp
property. At runtime, it’s undefined
because auto mocking doesn’t see it as a function so it ignored it.
Question: How to properly mock public properties on mocks without giving up auto mocking?