【问题标题】:Unit testing express route callback - mock res object单元测试快速路由回调 - 模拟 res 对象
【发布时间】:2018-02-21 17:09:36
【问题描述】:

我很难理解如何对呈现 html 文件的简单快速获取请求进行单元测试。

在我的设置中,当我收到关于未设置视图引擎的错误时,当我运行我的代码时。

我想做的只是检查“res.render”函数是否已被调用并模拟它,所以它实际上并没有做它应该做的事情。

route.js

module.exports = function(router) {

    router.get('/test', function(req, res, next) {
        console.log("Hi");
        res.render('test/test', { current: "current"});
    });
};

test.js

const request = require('supertest');
const sinon = require('sinon');
const express = require('express');
const app = express();
const routes = require('../../routes/route')(app);
describe('My routes', function () {

    before(function() {
        return this.spy = sinon.spy(app, 'render');
    });

    after(function() {
        return this.spy.restore();
    });

    it('should render to /test', function(done) {

        var res = { render: sinon.spy() };

        request(app)
            .get('/test')
            .expect(200, done)
    });
});

它在 res.render('test/test') 行上失败了,我真的不希望这条线执行我想以某种方式模拟它?

我想我遗漏了一些明显的东西!

谢谢大家 乔伊

【问题讨论】:

  • 你能发布你得到的实际错误吗?
  • 你能否使用邮递员或其他工具检查相同的网址是否获得 200 状态@Joey

标签: javascript node.js unit-testing express mocha.js


【解决方案1】:

您收到此错误的原因应该很清楚,因为您在尝试运行 render() 方法时没有在您的 Express 应用程序上设置 view engine

来自模板引擎的 Express 文档(显然将以下内容替换为您在应用程序中使用的引擎):

app.set('views', './views') // specify the views directory
app.set('view engine', 'ntl') // register the template engine

至于模拟渲染方法,你可能想看看https://github.com/danawoodman/sinon-express-mock 在 Express 中模拟你的请求和响应对象。即使您不想使用该软件包,您也可以查看源代码以了解他们是如何做到的,以及这是否符合您想要完成的目标。

【讨论】:

    【解决方案2】:

    问题在于,当您应该“要求”在真实代码中的其他地方使用的现有应用程序时,您创建了一个全新的快速应用程序。您的路线位于真正的快递应用程序中,因此到达它们的唯一方法是测试真正的快递应用程序。在您当前的设置中,即使您通过设置所有需要的属性来解决错误,您仍然需要复制您在真正的 express 应用中放入的所有内容。

    从 test.js 中删除

    const express = require('express');
    const app = express();
    

    上面的代码是创建一个空的应用程序,这不是你想要测试的。

    将其替换为

     const app = require('../../../app').app //customize for your file system
    

    上面的代码是一个示例,但想法是您的const app 被测需要指向您实际应用程序中的 express 实例。因此,如果您的主应用程序文件是 server.js 并且它比您的测试文件高 3 级,那么在您的路由测试中您需要使用

    const app = require('../../../server.js).app 
    

    假设你调用了你的 express 实例应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多