Ziast
Ziast

Reputation: 83

Clearing collection before testing with Mocha

I am writing unit tests for my Node.js app using Mocha, Chai, and Mongoose. The tests themselves work if the collection is empty(as desired), but I'm having trouble clearing the collection before testing.

let mongoose = require("mongoose");
let Subject = require('../Subject/subject');

//Require the dev-dependencies
let chai = require('chai');
let chaiHttp = require('chai-http');
// let server = require('../server');
let server = "http://localhost:3000"
let should = chai.should();

chai.use(chaiHttp);

describe('subjects', () => {
  before((done) => { //Before each test, empty the database
    Subject.remove({})
    done();         
  });

  describe('/GET subject', () => {
    // working test
  });

  describe('/POST subject', () => {
    // working test
  });

  describe('/GET subject', () => {
    // working test
  });
});

I have also tried variations of

Subject.deleteMany({}, (err) => console.log(err));

and

Subject.find({}, (subject)=>{
   subject.remove({}).exec()
})

inside the before block to no avail. I have tried the removes outside of the before block as well, just in case. If I console.log(Subject.remove({})) I get the Subject object, so it's able to access it, just not actually doing anything permanent with it.

I've been at this a couple hours now and haven't gotten any closer to figuring it out, so all help is appreciated.

Upvotes: 1

Views: 1359

Answers (2)

Estus Flask
Estus Flask

Reputation: 222750

Since both Mocha and Mognoose support promises for asynchronous blocks, they can be seamlessly used instead of calling done directly. In this case a promise should be returned:

  before(() => Subject.remove({}));

Upvotes: 0

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

Try waiting for the callback of the remove call like so

before((done) => { //Before each test, empty the database
 Subject.remove({}, done);
});

Upvotes: 2

Related Questions