Below is the solution:
UserManagementService.ts
:
export const createUser = async body => {
console.log("... saving user to database ...");
};
export const getUserById = async id => {
console.log("... fetching user from the database ...");
};
authentication.ts
:
import * as UserManagementService from "./UserManagementService";
export async function authenticate(userService: typeof UserManagementService) {
await userService.getUserById("1");
await userService.createUser({ name: "test" });
}
authentication.test.ts
:
import * as UserManagementService from "./UserManagementService";
import { authenticate } from "./authentication";
jest.mock("./UserManagementService", () => {
const mockUserService = {
getById: jest.fn(),
create: jest.fn()
};
return mockUserService;
});
describe("UserManagementService", () => {
it("should authenticate successfully", async () => {
await authenticate(UserManagementService);
expect(UserManagementService.getById).toBeCalledWith("1");
expect(UserManagementService.create).toBeCalledWith({ name: "test" });
});
});
Unit test results with complete coverage:
PASS src/stackoverflow/59035729/authentication.test.ts (13.16s)
UserManagementService
✓ should authenticate successfully (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 available at: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59035729