有没有一个模块轻松地模拟req / res对象的unit testing连接样式处理程序?

我在node.js中编写了一个应用程序,其中包含一些连接样式端点处理程序(函数(req,resp)),并希望针对它们编写一些unit testing,而无需运行完整的应用程序。

我知道我可以“简单地”推动任何我手动写入的设备,但是我想知道是否有任何库可以帮助我更快地生成这些设备。

编辑:进一步解释我想要什么,我想在我的unit testing只执行我的处理程序(而不是我的应用程序),为此,我需要一个假的需求和水库。 那些是我想嘲笑的两件东西。

我目前正在使用摩卡作为testing运行器和核心断言模块。

如果你以某种方式定义你的路线,那么你可以使用supertest来testing路线。

testing

 var app = require('./real-or-fixture-app'); //depends on your setup require('routeToTest')(app); var request = require("supertest"); describe("Test", function(){ it("should test a route", function(done){ request(app) .post("/route") .send({data:1}) .expect(200, done); }); }); 

路线定义

 module.exports = function(app){ app.get("/route", .... }; 

我不太确定这是否真的是你正在寻找的东西,但它是一种单独testing你的路线的方法。

我知道这个问题是旧的,但现在做这个伟大的方式是Supertest https://github.com/visionmedia/supertest

如果你曾经使用Djangotesting客户端库,它的工作就像这样。 它模拟运行你的意见/路线,让你得到一个testing场景更像是如果一个实际的浏览器打你的看法。 这意味着需求和资源被嘲笑,但performance在一个预期的方式。 它比Selenium更快(或者比如使用Webdriver的量angular器)。

正如你可能知道的那样,把你的逻辑从你的路由中移出是一个好主意,这样它就可以单独进行unit testing。 我真的不考虑使用Supertest作为unit testing,因为你总是testing多个代码单元。

您可能会对我使用Sinon创build模拟请求/响应的小包感兴趣。

本质上它只是创build一个模仿标准req / res的对象,并用spysreplace你可以检查的方法。

从自述文件:

你的testing:

 import route from '../src/foo' import { mockReq, mockRes } from 'sinon-express-mock' describe('my route', () => { it('should foo the bar', () => { const body = { body: { foo: 'bar', }, } const req = mockReq(body) const res = mockRes() route(req, res) expect(res.json).to.be.calledWith({ foo: body.foo.bar }) }) }) 

src/foo.js

 export default (req, res) => { res.json({ foo: req.body.bar }) } 

https://github.com/danawoodman/sinon-express-mock