CodePark/ questions / Classes in NestJS & testing
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Classes in NestJS & testing

This test fails: the spy is never called, and the real find runs. Why?

class UserService {
  find = async (id: string) => this.repo.findById(id);
  // ...
}

const spy = jest.spyOn(UserService.prototype, "find");
const service = new UserService(repo);
await service.find("u1");
expect(spy).toHaveBeenCalled();
find is an arrow class field, so it lives on each instance, not on the prototype

find is an arrow-function field. The constructor creates it on each instance, so UserService.prototype.find doesn't exist for Jest to replace. Spy on the instance instead: jest.spyOn(service, "find"). Or make find a normal method.

"
jest.spyOn does not work with async functions" is wrong. Spies work with any function. The problem is only where the function lives.