I'm interested in automating the process of utilizing an object's toString() method when it is implicitly converted to a string. Let's consider this example class:
class Dog {
name: string;
constructor(name: string) {
this.name = name;
}
public toString(): string {
return `${this.name} is my friend`;
}
}
In the following test, you'll notice that the second assertion fails:
test.only("Dog", () => {
const dog = new Dog("buddy");
expect(dog.toString()).toBe("buddy is my friend");
expect(dog as any as string).toBe("buddy is my friend"); // fails
});
The error message reads:
expect(received).toBe(expected) // Object.is equality
Expected: "buddy is my friend"
Received: {"name": "buddy"}
(Note: using .toEqual
instead of .toBe
also results in failure.)
My goal is for this assertion to pass. Is there a way to adjust the Dog class to enable this behavior? Any suggestions or insights on whether this is achievable?