4
votes

I wanted to start testing express routes today but I can figure out how to test rendering jade views.

Here is my code:

Route:

  router.get('/', function(req: any, res: any) {
    res.render('index', { title: 'Express' });
  });

Test:

 describe('GET / ', () => {
   it('renders index', (done) => {
     request(router)
       .get('/')
       .render('index', { title: 'Express' })
       .expect(200, done);
   });
 });

Of course .render causes an error. How should I test rendering?

2
Check if the outcome of the request matches what should have been rendered? - robertklep

2 Answers

-1
votes

You might need to configure the rendering engine in your test. Check the response body for something like Error: No default engine was specified and no extension was provided..

I was able to use:

// Setup Fake rendering
beforeEach(() => {
  app.set('views', '/path/to/your/views');
  app.set('view engine', 'ext');
  app.engine('ext', (path, options, callback) => {
    const details = Object.assign({ path, }, options);
    callback(null, JSON.stringify(details));
  });
}

it('your awesome test', async () => {
  const res = await agent.get('/route').type('text/html');

  // This will have your response as json
  expect(res.text).to.be.defined;
});
-1
votes

You can use chai instead

const chai = require('chai');
const chaiHttp = require('chai-http');
const expect = chai.expect;
chai.use(chaiHttp);

    describe('Route Index', () => {
        it('should render the index view with title', (done) => {
            chai.request(app)
                .get('/')
                .end((err, res) => {
                    expect(res).to.have.status(200);
                    expect(res).to.have.header('content-type', 'text/html; charset=utf-8'); 
                    expect(res.text).to.contain('Express');
                    done();
                });
        });
    });