Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB / Mongoose Unit Testing - Best practice? [closed]

I'm writing a npm package to import GIS data into MongoDB via mongoose. I've written unit tests using mocha to test the data transformations that happen BEFORE the mongoose model is saved.

I'd like to be sure that all the mongoose data got saved correctly to the database (including any updates that needed to occur). What would be the best practice, in this case?

My intuition create a test collection, insert all the records, ensure that it looks the way I expect it to look, and drop the collection.

like image 915
Ashwin Balamohan Avatar asked Dec 19 '22 07:12

Ashwin Balamohan


1 Answers

Yes, setting up and tearing down all the collections in the database is necessary for ensuring there are no side effects between unit tests. In practice, this means a beforeEach() where you reconnect to the database and drop all collections, and an afterEach() where you disconnect from the database.

Some deeper information: What you are trying to do here is integration testing, where you are testing the actual integration between your code and mongo. Unit tests are tests that never call the database or other resources. More info on this here: What's the difference between unit tests and integration tests? For me, I separate them into tests/unit and tests/integration.

I'm not aware of any packages or libraries that do this for you, but take a look at this tutorial for one way to go about this.

like image 100
Jorge Aranda Avatar answered Dec 21 '22 21:12

Jorge Aranda