Is there a module for easily mocking req / res objects for unit testing a join style handler?

I am writing an application in node.js that includes some connection-style endpoint handlers (function (req, resp)) and would like to write some unit tests against them without requiring the application to run completely.

I know that I can "just" click on any device that I manually record into it, but I was wondering if there was any library to help me generate these lights faster.

EDIT: to further explain what I want, I would like only my handler (not my application) to execute in my unit test, and for this I needed fake req and res. These are the objects that I would like to make fun of.

I am currently using mocha as a test runner and kernel confirmation module.

+6
source share
3 answers

If you defined your routes in such a way as to pass the app function to a function, you can use supertest to check the route.

Test

 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); }); }); 

Route definition

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

I'm not quite sure if this is really what you are looking for, but it is a way to check your routes separately.

+2
source

I know this question is old, but now this is a great way: Supertest https://github.com/visionmedia/supertest

If you've ever used the Django test client library, it works a lot. It simulates the launch of your views / routes, so that you get a test script more, as if the actual browser fell into your opinion. This means that req and res are mocking, but behaving as expected. This is faster than Selenium (or, for example, a protractor that uses Webdriver under covers).

As you probably know, this is a great idea - get your logic out of your routes so that it can be tested separately. I really don't consider using Supertest as unit testing, as you invariably test more than one block of code.

+2
source

You might be interested in the small package I am compiling, which makes it easy to create mock requests / responses using Sinon.

Essentially, it simply creates an object that mimics the standard req / res from an expression and replaces the method with spys, which you can test.

From README:

Your test:

 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 }) }) }) 

Content src/foo.js :

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

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

+1
source

All Articles