I'm using TypeORM.
It works fine at the local with real DB connection.
But when I run the test with Jest, the test gets failed.
I mocked the TypeORM method and expected this methods to be called.
but test is failing on expect(typeorm.getRepository(Covid).save).toHaveBeenCalled();
I cannot understand why this test code is failing.
Does anyone know the solution?
Here is the code.
describe('getCoronaData', () => {
it('should get a Covid Status data and return it', async () => {
typeorm.getRepository = jest.fn().mockReturnValue({
findOne: jest.fn().mockResolvedValue(null),
create: jest.fn(),
save: jest.fn(),
});
await getCoronaData();
expect(typeorm.getRepository).toHaveBeenCalledWith(Covid);
expect(typeorm.getRepository(Covid).findOne).toHaveBeenCalled();
expect(typeorm.getRepository(Covid).save).toHaveBeenCalled(); // this expect result is making an error
// Expected number of calls: >= 1
// Received number of calls: 0
});
});
export const getCoronaData = async () => {
try {
const covidStatus = [
{
city: 'city',
totalCases: '100',
increasedCases: '100',
date: 'time',
},
];
const covidRepository = getRepository(Covid);
covidStatus.forEach(async (status) => {
const exist = await covidRepository.findOne({
where: { city: status.city },
});
if (!exist) {
return await covidRepository.save(
covidRepository.create({
city: status.city,
totalCases: status.totalCases,
increasedCases: status.increasedCases,
date: status.time,
})
);
} else {
return await covidRepository.save([
{
id: exist.id,
totalCases: status.totalCases,
increasedCases: status.increasedCases,
date: status.time,
},
]);
}
});
} catch (err) {
console.error(err);
return;
}
};
Aucun commentaire:
Enregistrer un commentaire