{

Typescript mock interface and async promise example


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

Typescript is an advanced to javascript with strong features like typesafe checking.

Jest is an unit testing framework like jasmine from Facebook

How to mock an interface in Jest?

Let’s declare an interface in typescript with enum being used in 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 Jest mock interface example

  • First create an 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 contains async promise

Let’s define an service with following method returns Promise

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

Here is an example for jest async method interface example

Here are steps for creating mock

  • First create a mock interface using jest.fn with method resolving to an object
  • Next assert check for mock object is defined
  • check 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 mock an interface in typescript with jest framework and also mocking an interface with async method.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.