I have below 2 methods.
searchCertificates()
is private methos which is called inside findAll()
.
method are
async findAll(queryCertificateDto: QueryCertificateDto): Promise<PaginatedResult> {
const { data, meta } = await this.searchCertificates(queryCertificateDto);
return {
data,
meta,
};
}
private async searchCertificates(
queryCertificateDto: QueryCertificateDto
): Promise<PaginatedResult> {
const {
page,
take,
certificateNo,
startDate,
endDate,
} = queryCertificateDto;
const query = this.certificateRepository.createQueryBuilder('certificate');
if (certificateNo) {
query.andWhere('certificate.certificateNo=:certificateNo', { certificateNo });
}
if (startDate && endDate) {
query.andWhere('CAST(certificate.createdAt as Date) BETWEEN :startDate AND :endDate', {
startDate,
endDate,
});
} else if (startDate) {
query.andWhere('CAST(certificate.startDate as Date)=:startDate', { startDate });
} else if (endDate) {
query.andWhere('CAST(certificate.endDate as Date)=:endDate', { endDate });
}
const [certificates, total] = await query
.orderBy('certificate.certificateNo', 'ASC')
.take(take)
.skip((page - 1) * take)
.getManyAndCount();
return {
data: certificates,
meta: {
total,
page,
last_page: Math.ceil(total / take),
},
};
}
I wrote below test case to cover startDate
useValue: {
find: jest.fn().mockReturnValue(certificate),
createQueryBuilder: jest.fn(() => ({
andWhere: jest.fn().mockReturnValue(certificate),
getManyAndCount: jest.fn().mockReturnValueOnce(certificate),
orderBy: jest.fn().mockReturnThis(),
take: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
page: jest.fn().mockReturnThis(),
})),
findOne: jest.fn().mockReturnValue(certificate),
save: jest.fn().mockReturnValue(new Certificate()),
softRemove: jest.fn().mockReturnValue(new Certificate()),
},
below is test case
it('return the Certificate list for start date', async () => {
const queryCertificateDto = new QueryCertificateDto();
queryCertificateDto.startDate = '23-MAR-2019';
const result = await service.findAll(queryCertificateDto);
expect(result['startDate']).toEqual(certificate.startDate);
});
It is getting failed.
I dont know even reason of it. Could you please help me to understand?
CodePudding user response:
Your getManyAndCount
mock should return a resolved value, and be mockResolvedValueOnce
so that it can be await
ed. It hsould also return an array of values, as you deconstruct the array into two parts, the certificates
and the total