Typescript mock interface and async promise example

In this tutorial, You learned how to test a mock interface in typescript.

Typescript is advanced to JavaScript with strong features like type safe checking.

Jest is a unit testing framework like jasmine from Facebook.

How to mock an interface in Jest?

Let’s declare an interface in typescript with an enum being used in the interface.

role.ts:

enum ROLE {
    ADMIN,
    SALES,
    FINANCE
}

user.ts:

export interface User {
  id: number;
  name: string;
  role: ROLE.ADMIN | ROLE.FINANCE | ROLE.SALES;
}

Here is an User.spec.ts for the Jest mock interface example.

  • First create a mock interface with all defined values
  • Check for mock object undefined and values asserted for expected
describe('User', () => {
    const mock = jest.fn<User, []>(() => {
        return {
            id: 1,
            name: 'john',
            role: ROLE.ADMIN,
        };
    });

    it('should check mock object', () => {
        const user = mock();
        expect(user).toBeDefined();

    });
    it('should check properties', () => {
        const user = mock();
        expect(user.name).toEqual('john');
        expect(user.role).toEqual(ROLE.ADMIN);
    });
});

How do you mock an interface that contains an async promise

Let’s define a service with the following method returns Promise.

interface UserService {
  getEmployee: () => Promise<any>;
}

Here is an example of the jest async method interface example.

Here are steps for creating mock

  • First, create a mock interface using jest. fn with a method resolving to an object
  • Next assert check for the mock object is defined
  • check to assert object promise method to check resolved value
let userServiceMock: UserService;

describe("UserService", () => {
  beforeAll(() => {
    userServiceMock.getEmployee = jest.fn(() =>
      Promise.resolve({
        id: 1,
        name: "john",
        role: ROLE.ADMIN,
      })
    );
  });

  it("should check mock object", () => {
    expect(userServiceMock).toBeDefined();
  });
  it("should check properties", () => {
    userServiceMock.getEmployee();
    expect(userServiceMock.getEmployee).toHaveBeenCalled();
    expect(userServiceMock.getEmployee.mock.results[0].value).resolves.toBe({
      id: 1,
      name: "john",
      role: ROLE.ADMIN,
    });
  });
});

Conclusion

You learned to mock an interface in typescript with jest framework and also mock an interface with the async method.