Testing an MEVN Application Chapter 9
There are two folders inside the test folder. One for unit testing, called unit, and another
for end-to-end testing, called e2e. We will start by writing the unit tests, which go under
the unit directory. The naming convention is appending the .spec part to the filename for
every file we will be writing tests for.
Writing tests for controllers
Let's get started with writing tests for the controllers we added. Create a folder called
controllers inside the test/unit/specs and create a new file inside it called
movies.spec.js. This will be the naming convention that we will follow while creating
the test files for any components: controllers, models, or Vue components—the actual
filename followed by .spec.js. This helps to maintain the readability of the code.
Let's first recap what we have in our movies.js file:
var Movie = require("../models/Movie");
module.exports.controller = (app) => {
// fetch all movies
app.get("/movies", function(req, res) {
Movie.find({}, 'name description release_year genre', function
(error, movies) {
if (error) { console.log(error); }
res.send({
movies: movies
})
})
})
// add a new movie
app.post('/movies', (req, res) => {
const movie = new Movie({
name: req.body.name,
description: req.body.description,
release_year: req.body.release_year,
genre: req.body.genre
})
movie.save(function (error, movie) {
if (error) { console.log(error); }
res.send(movie)
})
})
}