jeudi 18 juin 2020

Mock methods of non default class exports in Jest Testing

I am trying to mock a simple function in my service class.

// hello.controller.ts

@Get()
  async getHello(): Promise<string> {
    const result = await this.helloService.getHello();
    return result;
  }

// hello.service.ts

export class HelloService { 
    getHello(): string {
       return 'Hello World!';
    }
}

// mock.ts

export const mockHello = jest.fn((): string => {
  return 'Hello World!';
});

jest.mock('../src/hello/hello.service', () => ({
 get getHello() {
    return mockHello;
   },
 }));

When I tested the API Execution, the service function gets called instead of the mock function. How do I make my mockfunction to be called instead of the service function. The mock works only when I make my function static and use the following code in mock.ts.

HelloService.getHello = mockHello;

How to make the above scenario work without making the function static.

Aucun commentaire:

Enregistrer un commentaire