Mocha: How to Test Express-Visualized Views

- Background

I am trying to test an Express application. This is a hobby for me, so I did not use Express to serve the JSON api (as is usually done).

- The problem

The problem is that I cannot find a way to test the content of the view to ensure that the page is actually displayed in the view file in the project itself.

- What have I tried

For example, I cannot check a simple index page because the jade file starts with extends layout . This makes verifying the execution of dynamic content difficult.

Does anyone have any suggestions on checking if the view is actually being viewed?

 it ('renders the index page', function(done) { var jade = require('jade'); var should = require('should'); var fs = require('fs'); supertest(app) .get('/') .expect(200) .end(function(err, res) { var rawJade = fs.readFileSync('./views/index.jade').toString(); res.text.should.equal(rawJade.convertToHtml()); // jade supports a function like this }); )}; 
+7
testing rendering mocha
source share
1 answer

There are, as usual, several ways to attack this problem. Before continuing, I urge you to ask yourself why you need it. Such tests are extremely fickle. If you make a small change, it will force you to rewrite the tests that now fail.

However, I think the easiest way to start adding tests that claim the correct rendering is https://github.com/cheeriojs/cheerio

A basic example would look like this:

 it ('renders the index page', function(done) { var should = require('should'); var cheerio = require('cheerio'); supertest(app) .get('/') .expect(200) .end(function(err, res) { err.should.not.be.ok(); res.should.be.ok(); var $ = cheerio.load(res.body); var header = $('h1:first'); header.should.equal('Hello World!'); done(); }); )}; 

Now you won’t check to see if the rendered view looks exactly the way you want (I mean, you could, but that would be tedious). But it also means that if you make small, minor changes, all of this will not crash. Instead, you can focus on checking that the key aspects of your user interface are displayed correctly (for example, the page name is with the correct spelling and class / identifier properties)

+1
source share

All Articles