Reputation: 2529
I have set up my environments as described here: https://medium.com/developer-circles-lusaka/how-to-write-an-express-js-server-using-test-driven-development-921dc55aec07
This means I am using the config package to select an environment.
What I would like to do is (re-)populate the database before each test is performed. I am expecting this can be done using the beforeEach() hook Mocha provides (I am using Mocha as a test runner).
My question is to what is an effective way of loading a bunch of data into the database all at once (I am using Mongoose in case that makes a difference. I do not know if I can omit that when inserting)? Preferably this is done in a separated file from the test.
Upvotes: 1
Views: 994
Reputation: 18919
Here is what I do:
Drop the database completely in beforeEach. You can get access to mongodb instance on you mongoose connection like: db.db.dropDatabase()
Create preconfigured data objects for my domain and save them in a module that I import - simple JavaScript objects. So I have data like data.users.vader and data.users.luke, data.products.deathStar etc
In my tests, I use chaihttp to hit routes with the data like:
let user = data.users.vader;
chai.request(server)
.post('/users')
.send(user)
.end((err, result) => {
if (err) {
return callback(err);
}
result.should.have.status(200);
result.body.status.should.eq(enums.status.success);
result.body.data._id.should.be.a('string');
result.body.data.name.should.eq(user.name);
result.body.data.email.should.eq(user.email);
Each unit test will drop the database and create the data needed. I start like this so that each test is independent.
You can also bulk load data using mongodb’s batchWriteItem
later on.
I also create functions that can be called within unit tests that will bulk load data using batchWriteItem
- this is mainly for perf testing queries etc
Upvotes: 2