Home > Blockchain >  Cannot mock a function in Jest
Cannot mock a function in Jest

Time:03-29

I'm trying to mock a service function that is being called by a controller class. I already mocked the service by using jest.mock() but I can't seem to mock the response of the service function. Can anybody spot what's wrong and how I should do it correctly?

MyController.ts

import {MyService} from '@service/MyService';

export class MyController {

  constructor() {  }

  public async queryDataById(id: string) {
    const myService = new MyService();
    return myService.query(id);
  }

}

MyController.test.ts

import { MyController } from "@controller/MyController";
import { MyService } from "@service/MyService";

jest.mock("@service/MyService")

describe("MyController", () => {
    let controller: MyController;

    describe("queryDataByid", () => {

        it("should return a response", async () => {
            const response = {
                id: 1,
                data: {}
            }
            MyService.query.mockReturnValue(response)
            const result = await controller.queryDataById(1)
            expect(result).toBeDefined()
            expect(result).toBe(response)
        })
    })
})

Error

Property 'query' does not exist on type 'typeof MyService'.ts(2339)

CodePudding user response:

Seems we wrongly specified the method name of MyService in test file.

MyService.queryDataById.mockReturnValue(response)

it is supposed to be query not queryDataById

Here is the sample working tests. I don't use jest.mock here, I used prototype mocking.

describe('MyController', () => {
  let controller: MyController = new MyController();

  describe('queryDataByid', () => {
    it('should return a response', async () => {
      const response = {
        id: 1,
        data: {},
      };

      MyService.prototype.query = jest.fn().mockReturnValue(response); // prototype mocking

      const result = await controller.queryDataById('1');

      expect(result).toBeDefined();
      expect(result).toBe(response);
    });
  });
});

Result

  MyController
    queryDataByid
      ✓ should return a response (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.433 s, estimated 2 s
Ran all test suites.

CodePudding user response:

Also, found another way to resolve this and it's by using jest.spyOn()

Sample:

spyQuery = jest.spyOn(MyService.prototype, "query")
spyQuery.mockResolvedValue(queryResult)
  • Related