Node.js 如何在try块中模拟错误并使用Jest捕捉它?就为了一次测试
我试图在其中一个路由中测试node.js应用程序中的catch块(请参见下文),因此我试图在try块中导致错误,但来自我的测试文件:Node.js 如何在try块中模拟错误并使用Jest捕捉它?就为了一次测试,node.js,unit-testing,jestjs,integration-testing,supertest,Node.js,Unit Testing,Jestjs,Integration Testing,Supertest,我试图在其中一个路由中测试node.js应用程序中的catch块(请参见下文),因此我试图在try块中导致错误,但来自我的测试文件: router.post('/', [auth, validate(validateRental)], async (req, res) => { const customer = await Customer.findById(req.body.customerId); if (!customer) return res.status(400).se
router.post('/', [auth, validate(validateRental)], async (req, res) => {
const customer = await Customer.findById(req.body.customerId);
if (!customer) return res.status(400).send('Invalid customer.');
const movie = await Movie.findById(req.body.movieId);
if (!movie) return res.status(400).send('Invalid movie.');
if (movie.numberInStock === 0) return res.status(400).send('Movie not in stock.');
let rental = new Rental({
customer: {
_id: customer._id,
name: customer.name,
phone: customer.phone
},
movie: {
_id: movie._id,
title: movie.title,
dailyRentalRate: movie.dailyRentalRate
}
});
try {
await new Fawn.Task()
.save('rentals', rental)
.update('movies', { _id: movie._id }, {
$inc: { numberInStock: -1 }
})
.run();
res.send(rental);
} catch (error) {
res.status(500).send('Something Failed.');
}
});
在我的测试文件中,我在postrent()函数中使用Jest和supertest:
it('should return 500 if something failed', async () => {
// want to create an error inside the try block to be catched so that res.status would be 500
const res = await postRental();
expect(res.status).toBe(500);
});
我怎样才能在这里进行一个干净的测试,并在try块中创建一个错误,只让这个测试通过