lundi 2 novembre 2020

Using mocha and chai for backend unit tests, how to clear the database before each test

I have a backend setup using Node.js, Express and MongoDB. I wrote two unit tests for one of my endpoints but encountered unexpected behavior. First, here is the code:

let chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../../../server')
const expect = chai.expect
chai.use(chaiHttp);

describe('POST /user/register', () => {
  it('should create a new user', (done) => {
    chai
    .request(server)
    .post('/user/register')
    .send({username: 'Bob', password: 'password123'})
    .end((err, res) => {
      expect(res.status).to.equal(201)
      done()
    })
  })

  it('should result in an error if there is no payload', (done) => {
    chai
    .request(server)
    .post('/user/register')
    .send({})
    .end((err, res) => {
      expect(res.status).to.equal(500)
      done()
    })
  })
})

On the should create a new user test, it passes on the first try, but fails on the 2nd because the user is persisted in the database, so my endpoint returns a 409 status code, not 201.

I know that I have to use a beforeEach call to clear the test database, I'm just not sure of the implementation after having searched around for a while.

Aucun commentaire:

Enregistrer un commentaire