【问题标题】:Testing REST API and rendering with EJS测试 REST API 并使用 EJS 进行渲染
【发布时间】:2017-03-24 10:54:25
【问题描述】:

考虑这种情况:

当您访问我的/ 页面时,服务器将使用如下 JSON 响应

res.json({
    message: 'Welcome home.'
});

为了测试这一点,我创建了一个文件 home.test.js 并像这样测试它:

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

chai.use(chaiHttp);

describe('GET /', () => {
    it('should respond with homepage', (done) => {
        chai
            .request(server)
            .get('/')
            .end((err, res) => {
                expect(res.status).to.equal(200);
                expect(res.body.message).to.equal('Welcome home.');
                done();
            });
    });
});

简单的测试通过了,一切都按计划进行。这是问题所在。稍后,当我想使用 ejs 渲染视图时,我的代码将更改为:

 res.render('index', { message: 'Welcome home.' });

所以现在我之前的测试不会通过,因为res.body.message 现在的值是undefined。既然响应将是 res.render(),我该如何实际测试呢?

【问题讨论】:

    标签: node.js express testing mocha.js ejs


    【解决方案1】:

    我认为您可以在呈现页面之前影响到请求正文的消息。您的代码将是这样的:

     res.body.message="Welcome home".
     res.render('index',{message:"welcome home"})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多