Reputation: 7121
I have finished building a CRUD application with 20 tests passing. I am using EJS to render the views and now I am having a problem with my tests.
As a simple example let's say that I was checking to see that when a GET request is sent to '/'
that a JSON would be sent like so res.json({message:'hello'})
so I could set up my tests in Mocha so that res.body.message equates to 'hello'.
However what if I wanted to render the index.ejs
page instead of sending a JSON. So it would look like res.render('index',{message:'hello'})
. How can I test res.render()
? or more specifically how can I test the object passed to res.render()
?
EDIT: The solution to this problem (and problems of this sort) can be solved by using a testing paradigm called FUNCTIONAL TESTING. Google it.
Upvotes: 1
Views: 2669
Reputation: 489
To test a http get essentially can be understood as a need to test a route. So, your test should include a expect clause (as to what to expect when the route is sought) and the response to validate, in this case a JSON object.
Using Mocha, you can describe the test as
it('should respond with JSON data', function (done) {
request(server)
.get('/about/jv')
.expect(200)
.end(function (err, response) {
assert.equal(response.header['content-type'], 'application/json; charset=utf-8');
assert.deepEqual(response.body, {
"data":{
"username":"hello"}
});
done();
});
});
Because you need a server to run a http request against, 'supertest', a node package is used to start your 'server.js' to initialize the server and test with request(server).
Check this - The GitHub repo has the complete test template for this requirement. It has a test for the returned JSON object as well.
Upvotes: 2