简体   繁体   中英

How to mock named exports in Jest with Typescript

I'm trying to mock UserService in Jest. Here how the service looks like:

// UserService.ts

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

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

My tests look like this:

// auth.test.ts

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

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

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

But then I got this error:

Cannot assign to 'getById' because it is a read-only property.

Here is the solution:

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

Unit test result with 100% coverage:

 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

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59035729

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM