6

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?

marcelovca90
  • 2,673
  • 3
  • 27
  • 34
Ivan Erlic
  • 391
  • 1
  • 4
  • 14

2 Answers2

0

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();
                });
        });
    });
Hervera
  • 584
  • 9
  • 17
  • Is `app` here simply a new express instance, like at the top of the test file `const app = new express()`? – 1252748 Aug 29 '20 at 16:37
-1

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;
});
smaclell
  • 4,568
  • 7
  • 41
  • 49