'Node Express JEST Supertest PUT and DELETE endpoints return 405 "Method Not Allowed"
I am running a simple test on Node with Express and suppertest. There are 10 tests of which POST and GET tests are running well (first 6 tests). The other four, having PUT and DELETE are returning 405 "Method Not Allowed". This is my code:
test('Should login existing user', async () => {
await request(app)
.post('/api/auth')
.send({
email: userOne.email,
password: userOne.password
})
.expect(200);
});
test('Should NOT login nonexisting user', async () => {
await request(app)
.post('/api/auth')
.send({
email: userThree.email,
password: userThree.password
})
.expect(400);
});
test('Should get profile for authenticated user', async () => {
await request(app)
.get('/api/auth')
.set('x-auth-token', userOne.token)
.expect(200)
});
test('Should NOT get profile for unauthenticated user', async () => {
await request(app)
.get('/api/auth')
.expect(401)
});
test('Should create a new user', async () => {
await request(app)
.post('/api/person')
.set('x-auth-token', userOne.token)
.send({ ...userTwo })
.expect(201);
});
test('Should NOT create a new user', async () => {
await request(app)
.post('/api/person')
.send({ ...userTwo })
.expect(401);
});
test('Should update user for autheticated user', async () => {
await request(app)
.put('api/person/2')
.set('x-auth-token', userOne.token)
.send({ role: 1})
.expect(200)
});
test('Should NOT update user for unauthenticated user', async () => {
await request(app)
.put('api/person/2')
.send({ role: 1})
.expect(401)
});
test('Should delete user for autheticated user', async () => {
await request(app)
.delete('api/person/2')
.set('x-auth-token', userOne.token)
.send()
.expect(200)
});
test('Should NOT delete user for unauthenticated user', async () => {
await request(app)
.delete('api/person/2')
.expect(401)
});
As I said above, the top six both with and without the authentication works fantastic. The bottom 4 with PUT and DELETE requests are returning 405 "Method Not Allowed". Testing the same routes with postman I have not experienced any issues. Both DELETE and POST methods are working as expected. Does anyone know what am I doing wrong? What am I overlooking? Thank you for all your help.
Solution 1:[1]
There is nothing wrong with the DELETE and PUT methods. The reason was a simple typo (missing a / in front of 'api/person/2' call). It was only unfortunate that this occurred only in DELETE and PUT methods making the debugging take longer thinking the issue is with the methods. The bug was much simpler. Path was incorrect.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | xyz83242 |
