0
Hello, I am learning to do api’s Rest tests and I came across a problem using chai and mocha, I was following this example in question: https://medium.com/@rafaelvicio/testando-api-Rest-com-mocha-e-chai-bf3764ac2797 Of course changing things to the api I had already written. The problem is that the POST method is getting pending always, according to something pending documentation does not mean it failed. But I would like to pass this test. My route is returning a json of what was created, so I didn’t quite understand why the test didn’t pass, someone can give me a help on that?
Link to the repository if it helps: https://github.com/ThiagoBussola/api-games
Code of the POST route
router.post("/game", async (req, res) => {
const title = req.body.title
const year = req.body.year
const price = req.body.price
try {
const gameCreated = await Game.create({
title: title,
year: year,
price: price
})
res.json(gameCreated)
} catch (err) {
console.log(err)
res.sendStatus(500)
}
})
Test code
describe("Teste POST game", () => {
it("deve criar um novo jogo"), (done) => {
let game = {
title: "Jogo criado pelo mocha",
year: 2020,
price: 178
}
chai.request('localhost:3033')
.post('/game')
.send(game)
.end((err, res) => {
res.should.have.status(200)
done()
})
}
})
Try changing the http status of the test from 200 to 201, as 200 indicates successful request, while 201 is Created.
– Rafael Costa
In repostan only your json, Voce should not put
res.status(201).json(gameCreated)
?201
to indicate that a resource has been created. Are you using CORS in your application? What are theallowedHeaders
allowed? There in your.end((err, res) => {...}
, before theres
, it would be nice to put aif(err) done(err)
see what went wrong.– Cmte Cardeal
Yes the application is using Cors, as for allowedHeaders, I do not know answer. Anyway, I put the res.status(201), I had done it before, it keeps coming as pending. And also put if(err)... without results, I will put the link to the repository in the question, maybe it helps
– Bussola