如何使用supertest和mocha测试express渲染

6

我希望今天开始测试Express路由,但我不知道如何测试Jade视图的渲染效果。

以下是我的代码:

路由:

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

测试:

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

当然,.render 会引起错误。我该如何测试渲染呢?

检查请求的结果是否与应该呈现的内容相匹配? - robertklep
2个回答

0

你可以使用chai代替

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();
                });
        });
    });

这里的 app 是否就是一个新的 express 实例,类似于在测试文件顶部的 const app = new express() - 1252748

-1

你可能需要在测试中配置渲染引擎。检查响应的body,看是否有类似于Error: No default engine was specified and no extension was provided.的内容。

我能够使用:

// 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;
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接