如何使用Typescript在Jest中模拟命名的导出

时间:2019-11-25 16:02:23

标签: typescript mocking jestjs

我正在尝试在Jest中嘲笑UserService。服务如下所示:

// UserService.ts

export const create = async body => {
  ... save to db  ...
}

export const getById = async id => {
  ... returns user from database ...
}

我的测试如下:

// auth.test.ts

import * as UserService from '../services/UserService';

jest.mock('../services/UserService');

describe('Authorization', () => {
  beforeAll(() => {
    UserService.getById = jest.fn();
  });
});

但是后来我得到了这个错误:

  

由于它是只读属性,因此无法分配给“ getById”。

1 个答案:

答案 0 :(得分:1)

这是解决方案:

UserService.ts

export const create = async body => {
  console.log("... save to db  ...");
};

export const getById = async id => {
  console.log("... returns user from database ...");
};

auth.ts

import * as UserService from "./UserService";

export async function auth(userService: typeof UserService) {
  await userService.getById("1");
  await userService.create({ name: "jest" });
}

auth.test.ts

import * as UserService from "./UserService";
import { auth } from "./auth";

jest.mock("./UserService", () => {
  const mUserService = {
    getById: jest.fn(),
    create: jest.fn()
  };
  return mUserService;
});

describe("UserService", () => {
  it("should auth correctly", async () => {
    await auth(UserService);
    expect(UserService.getById).toBeCalledWith("1");
    expect(UserService.create).toBeCalledWith({ name: "jest" });
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/59035729/auth.test.ts (13.16s)
  UserService
    ✓ should auth correctly (8ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 auth.ts  |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.499s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59035729