无法在 Jest 中模拟函数

Cannot mock a function in Jest

我正在尝试模拟由控制器 class 调用的服务函数。我已经使用 jest.mock() 模拟了该服务,但我似乎无法模拟服务功能的响应。任何人都可以发现问题所在以及我应该如何正确地做到这一点吗?

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)
        })
    })
})

错误

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

似乎我们在测试文件中错误地指定了 MyService 的方法名称。

MyService.queryDataById.mockReturnValue(response)

应该是query而不是queryDataById

这是示例工作测试。我这里没有用jest.mock,我用的是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);
    });
  });
});

结果

  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.

另外,找到了另一种方法来解决这个问题,那就是使用 jest.spyOn()

样本:

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