Unit testing Express API
Models using sequelize-test-helpers, and controllers using sinonjs.
This is Part 8 of multi-part series on ExpressJS.
You can find Part 1 here. It talks about building a basic express api and setting up mocha for testing.
You can find Part 2 here. It talks about setting up PostgreSQL, sequelize for connecting express api with databases.
You can find Part 3 here. It talks about setting up associations (has many as well as belongs to) between two models.
You can find Part 4 here. It talks about setting up user authentication based on email and password.
You can find Part 5 here. It talks about using json web token (JWT) to protect a route.
You can find Part 6 here. It talks about advanced associations (many-to-many-through) and through/junction tables.
You can find Part 7 here. It talks about refactoring express api into a RESTful app.
To add unit tests, we first move our request specs to request
folder, and create models
and controllers
folders to hold our unit tests.
Let’s first test our post
and user
models.
Testing Models
To test models, we will use sequelize-test-helpers
which, as the name suggests, will help us with testing sequelize models.
npm i sequelize-test-helpers
For models, we will test
- Properties/columns
- Associations
Check out the models.post.spec.js
below —
Similarly, we will write models.user.spec.js
sequelize-test-helpers
provides a really powerful set of matchers, and makes unit testing models much easier.
Testing controllers
To test controller methods, we utilize sinonjs, which provides
Standalone test spies, stubs and mocks for JavaScript.
Works with any unit testing framework.
npm i sinon
The test for controller.posts.spec.js
So we basically replace getAllPosts
or getSpecificPost
method by using sinon (called stubbing) and provide our own response. Then we confirm that each relevant function is called/utilized by the controller by spying on it.
We also need to stub req
and res
here.
Once our work is done, we restore the stub to normal.
Similarly for controllers.users.spec.js
All our tests go green.
Craft Academy is a Tech Education Provider that aims to bring new talent to the market and help to solve the shortage of tech workers. We are founded on the belief that modern development standards, agile methodologies, and business skills are fundamental for IT professionals.
Our primary service is a 12-week coding bootcamp designed to provide individuals with a foundation of skills that allows them to enter the industry as junior developers.
With that foundation, our learners find employment in various industries or start their own businesses that bring new innovations to the market.
Would you like to know more about what we do? Follow us here on Medium, Facebook, Twitter or visit our website.