Full-Stack Web Development with Vue.js and Node

(singke) #1
Testing an MEVN Application Chapter 9

// 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)
})
})
}

In the preceding code, each API call needs a request and a response object, which we need
to mock. For this purpose, we have sinon. sinon provides us with a mechanism


to stub and mock the requests.


The three major methods that sinon provides are spies, stubs, and mocks:


Spies: Spies helps to create fake functions. We can use spies to track whether the
functions are executed or not.
Stubs: Stubs helps us to make functions return whatever we want. This is useful
when we want to test different scenarios for the given function.
Mocks: Mocks are used to fake network connections. They help to create a
dummy class instance, which helps to set the predetermined expectations.

Let's write a test for a get call in the movies controller:


// 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
})
})
})
Free download pdf