【问题标题】:How to test express rendering with supertest and mocha如何使用 supertest 和 mocha 测试快速渲染
【发布时间】:2016-09-02 20:26:04
【问题描述】:

我今天想开始测试快速路线,但我可以弄清楚如何测试渲染翡翠视图。

这是我的代码:

路线:

  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 会导致错误。我应该如何测试渲染?

【问题讨论】:

  • 检查请求的结果是否与应该呈现的匹配?

标签: node.js express mocha.js supertest


【解决方案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;
});

【讨论】:

    【解决方案2】:

    您可以改用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()
    猜你喜欢
    • 2016-06-05
    • 2018-02-16
    • 1970-01-01
    • 2020-08-21
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多