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.
In this tutorial, You learned how to test a mock interface in typescript.
Typescript is advanced to javascript with strong features like typesafe checking.
Jest is a unit testing framework like jasmine from Facebook.
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
.
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);
});
});
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
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,
})
});
});
You learned to mock an interface in typescript with jest framework and also mock an interface with the async method.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts