Home > Back-end >  How can I unit test chained function call?
How can I unit test chained function call?

Time:11-01

I've been struggling with how I can unit test a scenario and I came across this issue multiple times. It has to do with mocking a method within a class that has a specific return type. Lets say we have a class:

export class ExampleService {

   async findUsers() : Promise<Users[]> {
      const repository = getRepository(repoConfig);
      return repository.find()
   };

}

And here is the Service I'm trying to test:

import { ExampleService } from './ExampleService.ts'

class ToBeTestedService{ 
  async findHomeOwners() : Promise<Users[]> {
  
    const exampleService = new ExampleService();
    const users = await exampleService.findUsers();
    homeOwners = users.map((user) => return user.home == true)); 
    return homeOwners;
  }
}

Don't mind the correctness of the code (its an example). So the issue I am facing is how to mock the findUsers method in the ExampleService. I am able to mock the whole service but then I am not able to mock the response to that method (since its set to undefined by default).

Here is my approach in the test file.

jest.mock('../ExampleService');

describe('Unit Test: Example Service', () => {

   test('findHomeOwners', async () => {
      
     const exampleService = new ExampleService();
     jest
     .spyOn(exampleService , 'findUsers')
     .mockImplementationOnce(() => {
        return ExampleServiceMock.findUsers();
      }); 
   }
}

I also created an ExampleServiceMock.findUsers which returns a promise of type User[] with test values. The problem here is that since I do not pass the instance of the class to the service, my mock implementation of the method does not seem to be applied. When debugging the ToBeTestedService I can see that exampleService.findUsers() always returns undefined.

Any ideia/suggestion on how I can overcome this? Thanks in advance

CodePudding user response:

So I managed to find an asnwer for my problem. If anyone is facing a similar problem, the way to go about it is to do the following:

jest
 .spyOn(ExampleService.prototype, 'findUsers')
 .mockImplementationOnce(() => {
    return ExampleServiceMock.findUsers();
  }); 

So what I am doing is that instead of mocking the method on the instance of the Example Service, now I am mocking the actual method within the class so when an instance of the class is created, the method with have the desired mock implementation

  • Related