auth/src/modules/oldauthentication/tests/unit/add-username.usecase.spec.ts

80 lines
2.5 KiB
TypeScript

import { classes } from '@automapper/classes';
import { AutomapperModule } from '@automapper/nestjs';
import { Test, TestingModule } from '@nestjs/testing';
import { AuthenticationProfile } from '../../mappers/authentication.profile';
import { UsernameRepository } from '../../adapters/secondaries/username.repository';
import { Username } from '../../domain/entities/username';
import { Type } from '../../domain/dtos/type.enum';
import { AddUsernameRequest } from '../../domain/dtos/add-username.request';
import { AddUsernameCommand } from '../../commands/add-username.command';
import { AddUsernameUseCase } from '../../domain/usecases/add-username.usecase';
import { Messager } from '../../adapters/secondaries/messager';
const addUsernameRequest: AddUsernameRequest = {
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
username: '0611223344',
type: Type.PHONE,
};
const addUsernameCommand: AddUsernameCommand = new AddUsernameCommand(
addUsernameRequest,
);
const mockUsernameRepository = {
create: jest
.fn()
.mockImplementationOnce(() => {
return Promise.resolve(addUsernameRequest);
})
.mockImplementation(() => {
throw new Error('Already exists');
}),
};
const mockMessager = {
publish: jest.fn().mockImplementation(),
};
describe('AddUsernameUseCase', () => {
let addUsernameUseCase: AddUsernameUseCase;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [AutomapperModule.forRoot({ strategyInitializer: classes() })],
providers: [
{
provide: UsernameRepository,
useValue: mockUsernameRepository,
},
{
provide: Messager,
useValue: mockMessager,
},
AddUsernameUseCase,
AuthenticationProfile,
],
}).compile();
addUsernameUseCase = module.get<AddUsernameUseCase>(AddUsernameUseCase);
});
it('should be defined', () => {
expect(addUsernameUseCase).toBeDefined();
});
describe('execute', () => {
it('should add a username for phone type', async () => {
const addedUsername: Username = await addUsernameUseCase.execute(
addUsernameCommand,
);
expect(addedUsername.username).toBe(addUsernameRequest.username);
expect(addedUsername.type).toBe(addUsernameRequest.type);
});
it('should throw an error if user already exists', async () => {
await expect(
addUsernameUseCase.execute(addUsernameCommand),
).rejects.toBeInstanceOf(Error);
});
});
});