Created
June 15, 2023 10:41
-
-
Save michmzr/abfe199e3eeb9796fd2bc1775d865dc2 to your computer and use it in GitHub Desktop.
Mocha + chai - rest api template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const chai = require('chai'); | |
const chaiHttp = require('chai-http'); | |
const { afterEach, describe, it } = require('mocha'); | |
chai.use(chaiHttp); | |
const expect = chai.expect; | |
// Server URL | |
const serverUrl = 'http://localhost:3000'; | |
describe('API Tests', () => { | |
let createdEntityId; | |
afterEach(async () => { | |
// Cleanup created resources | |
if (createdEntityId) { | |
await chai.request(serverUrl) | |
.delete(`/api/entities/${createdEntityId}`); | |
} | |
}); | |
it('should create an entity', async () => { | |
const res = await chai.request(serverUrl) | |
.post('/api/entities') | |
.send({ name: 'Test Entity' }); | |
expect(res).to.have.status(200); | |
expect(res.body).to.have.property('id'); | |
createdEntityId = res.body.id; | |
}); | |
it('should get an entity by ID', async () => { | |
// Assuming we have an existing entity with ID 123 | |
const entityId = 123; | |
const res = await chai.request(serverUrl) | |
.get(`/api/entities/${entityId}`); | |
expect(res).to.have.status(200); | |
expect(res.body).to.have.property('id', entityId); | |
}); | |
it('should update an entity by ID', async () => { | |
// Assuming we have an existing entity with ID 123 | |
const entityId = 123; | |
const res = await chai.request(serverUrl) | |
.put(`/api/entities/${entityId}`) | |
.send({ name: 'Updated Entity' }); | |
expect(res).to.have.status(200); | |
expect(res.body).to.have.property('id', entityId); | |
expect(res.body).to.have.property('name', 'Updated Entity'); | |
}); | |
it('should delete an entity by ID', async () => { | |
// Assuming we have an existing entity with ID 123 | |
const entityId = 123; | |
const res = await chai.request(serverUrl) | |
.delete(`/api/entities/${entityId}`); | |
expect(res).to.have.status(200); | |
expect(res.body).to.have.property('message', 'Entity deleted successfully'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment