class-mocker
v1.0.3
Published
Class-mocker is library for mocking dependencies.
Downloads
1
Maintainers
Readme
class-mocker
Class-mocker is library for mocking dependencies.
Installation
$ npm i --save-dev class-mocker
Usage example
For example you has controller and repository. The controller is curled from the repository.
Repository example
export class UserRepository {
private readonly data: Map<number, User> = new Map<number, User>();
constructor() {
// Initialize data for emulation requests to database
for (let id = 0; id < 5; id++) {
this.data.set(id, new User(id, `User${id}`, `P@$$W0RD`,`user${id}@test-mail.it`));
}
}
async findById(id: number): Promise<User> {
// Emulate request to database
await awaitTimeout(1000);
return this.data.get(id);
}
async findAll(): Promise<User[]> {
// Emulate request to database
await awaitTimeout(1000);
return Array.of(...this.data.values())
}
}
function awaitTimeout(timeout: number): Promise<void> {
return new Promise<void>(resolve => setTimeout(resolve, timeout));
}
Controller example
export class UserController {
constructor(private readonly userRepository: UserRepository) {
}
async find(id: number): Promise<Response<User | string>> {
try {
const user = await this.userRepository.findById(id);
if (!user) {
return new Response(404, 'Not found.');
}
return new Response(200, user);
} catch (e) {
return new Response(500, 'Internal server error.');
}
}
async findAll(): Promise<Response<User[] | string>> {
try {
return new Response(200, await this.userRepository.findAll());
} catch (e) {
return new Response(500, 'Internal server error.');
}
}
}
Mock creation
Mock by return
const userRepositoryMock = new Mock(UserRepository)
.expect('findAll', {return: []});
Mock on call
const userRepositoryMock = new Mock(UserRepository)
.expect('findById', {call: (id: number) => {
expect(id).toBe(2); // Check argument
return new User(2, 'ReplacedUser2', 'P@$$W0RD', '[email protected]');
}});
Mock on thrown error
const userRepositoryMock = new Mock(UserRepository)
.expect('findAll', {throw: new Error('Database is not available')});
Mock by order
const userRepositoryMock = new Mock(UserRepository)
.expect('findById', {
at: 1,
return: new User(4, 'ReplacedUser4', 'P@$$W0RD', '[email protected]'),
})
.expect('findById', {at: 2, return: null});
Enjoy!