Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocha: How to test Express rendered views

-- Background

I'm trying to test an Express application. This is a hobby project for me, so I have not used Express to serve a JSON api (as it is usually done).

-- The Problem

The issue is, I can't figure out a way to test the view's content to ensure that the page is actually being rendered against the view file in the project itself.

-- What I've Tried

For instance, I can't test a simple index page, because the jade file starts with extends layout. This makes it difficult to test if dynamic content is being rendered.

Does anyone have suggestions for testing whether the view is actually being rendered?

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
    });
)};
like image 483
CisBae Avatar asked Apr 17 '15 09:04

CisBae


1 Answers

There are, as usual, several ways to attack this problem. Before I continue, I encourage you to ask yourself why you need to do this. Tests like this are extremely fickle. If you make some tiny change, it is going to force you to rewrite tests that are now failing.

That said, I think the easiest way to start adding tests that assert proper rendering is with https://github.com/cheeriojs/cheerio

A basic example would look like the following:

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 aren't going to be testing whether the rendered view looks exactly like what you want (I mean you could but that would be tedious). But that also means that if you make some small insignificant change, the whole thing won't come crumbling down. Instead you can focus on testing whether key aspects of your UI are rendering properly (e.g. The title of the page is there, with the correct spelling and class/id properties)

like image 123
aray12 Avatar answered Sep 21 '22 16:09

aray12