node.js - 测试 REST API 并使用 EJS 渲染

标签 node.js express testing mocha.js ejs

考虑这个场景:

当您访问我的/ 页面时,服务器将使用如下所示的 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 来呈现 View 时,我的代码将更改为:

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

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

最佳答案

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

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

关于node.js - 测试 REST API 并使用 EJS 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997649/

相关文章:

javascript - 将变量设置为 Mongoose Find 的结果

mysql - NodeJS + Socket.IO + Mysql

android - 使用 localhost 在移动设备的浏览器中测试移动 Web 应用程序

javascript - 如何提供 html、css 和 js,同时将 module.export 内的路由保留在不同的文件中?目前仅提供 html

c# - 使用 C# 类中的填充值生成模拟 XML 的工具

node.js - Expressjs + Mongoose - 该网页不可用?

mysql - Express - Sequelize - 在查询中添加外表字段

node.js - 如何在expressjs中触发路由器错误处理程序而不是默认错误处理程序

java - 编写多个测试函数会对除第一个之外的每种情况给出 NullPointerException

zend-framework - PHPUnit代码覆盖率显示单元测试的代码覆盖率?