Reputation: 7105
I have a controller like this
async create(@Body() dto: myDTO,@Req() request, @I18n() i18n?: I18nContext): Promise<MyEntity>
{
return this.Myservice.create(dto, request, i18n);
}
and service like this:
async create(dto: CreateApplicationDTO, request?, i18n?): Promise<Application> {
const MyEntity= this.repository.create(dto);
request.message = i18n.t('common.added_successful');
return this.repository.save(MyEntity);
}
and service.spec file this :
it('check number of created applications', async () => {
await service.create(myDto);
expect(await service.findAll()).toHaveLength(1);
});
When I start test show me this error
TypeError: Cannot set properties of undefined (setting 'message')
41 | return this.repository.save(newApplication);
42 | } catch (e) {
> 43 | return request.message = e.message;
| ^
44 | }
45 |
46 | }
I know I should send request
and i18n
to service but I don't know how mock them and send them to service in my spec
file
Upvotes: 0
Views: 1551
Reputation: 70490
You've set request
to be optional but set a property on it regardless if it is populated or not. You need to make sure that request
has a value before you try to assign to it. For simplicity sake, because you don't give it a type, it could just be {}
and then {}.message =
will be valid.
As for i18n
in your create
method you use the object method t
so you need the mock to have a t
method. Something like { t: jest.fn(() => 'some value') }
should be enough to get the test going with a mock.
Having stronger typings will help you though, even if it means it is harder to make mocks. You could use a tool like @golevelup/ts-jest
can be used to create full mocks off of types alone
Upvotes: 1