Komo
Komo

Reputation: 2138

Unit/Integration testing Express REST API, mongoose, mocha, sinon, chai, supertest

I'm quite confused about unit testing an Express REST API using mongoose. I've heard about supertest, sinon, chai and mocha.

I want to write tests to :

1) Test the API interface :

Create a supertest server and make requests on it (GET /users, POST /users for example) and check that it calls the right routes.

2) Test the mongoose queries :

When a route is called, I want to check that the right mongoose function is called (find, findById) and that it returns the right data (fake data), something like :

when User.findId is called, return fake user (data defined in beforeEach). Is it what sinon stubs are for ?

3) Integration tests : Create a test database (created on test run), fill it and clean it when tests are finished. Make API calls (GET users, PUT users/1202082, DELETE users/1202082...) on a supertest server and check that the right data is read, created, updated, deleted...

Is it the way to go ? Simple examples for each case would be quite nice !

Upvotes: 4

Views: 1301

Answers (1)

Gon
Gon

Reputation: 627

If what you want is test static's and method's of certain Mongoose model, I would recommend you to use sinon and sinon-mongoose. (I guess it's compatible with chai)

This way, you won't need to connect to Mongo DB and return fake data easily.

You can find working (and simple) examples on the sinon-mongoose repo.

Upvotes: 1

Related Questions