Вот рабочий пример:
user.services.ts
:
import bcrypt from 'bcrypt';
const logEvent = { emit(event, payload) {} };
class UserService {
user;
constructor(user) {
this.user = user;
}
async updateUser(user) {
let result;
try {
const pass = bcrypt.hashSync(user.userPassword, 9);
result = await this.user.findByPk(user.id);
if (result) {
result.userPassword = pass;
await result.save();
return result;
}
} catch (e) {
logEvent.emit('APP_ERROR', {
logTitle: '[UPDATE-USER-FAILED]',
logMessage: e,
});
throw new Error(e);
}
}
}
export { UserService };
user.services.test.ts
:
import { UserService } from './user.services';
describe('60468548', () => {
it('should update user that input by', async () => {
const dataInput = { id: 1, username: 'teguh', userPassword: 'apake' };
const userModelInstanceMock = { save: jest.fn() };
const userModelMock = { findByPk: jest.fn().mockResolvedValueOnce(userModelInstanceMock) };
const userService = new UserService(userModelMock);
const actual = await userService.updateUser(dataInput);
expect(userModelMock.findByPk).toBeCalledWith(1);
expect(userModelInstanceMock.save).toBeCalledTimes(1);
});
});
Результаты модульных испытаний с отчетом о покрытии:
PASS src/examples/stackoverflow/60468548/user.services.test.ts
60468548
✓ should update user that input by (36ms)
------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
------------------|----------|----------|----------|----------|-------------------|
All files | 84.62 | 50 | 66.67 | 84.62 | |
user.services.ts | 84.62 | 50 | 66.67 | 84.62 | 22,27 |
------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.78s