未加星标

Mocking ExpressJS Request and Response objects

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

When unit-testing ExpressJS route controllers and middleware you need to make dummy req and res objects to pass in as parameters. The req param needs a bunch of properties, most-typically body , query , and params objects, as well as the get function for accessing headers. The res param typically needs end , json , send , and status functions, as well as whatever else your function uses. In the case of the status function, your fake res object needs to ensure its status function is chainable.

To make this simple I have published mock-req-res , which exposes mockRequest and mockResponse functions your unit-tests can use to generate consistent and useful mock req and res objects.

The mockrequest const req = mockRequest(options)

The options can be whatever you wish. The defaults are:

body: {}, cookies: {}, query: {}, params: {}

The get function is supplied as a sinon stub .

The mockresponse const res = mockResponse(options)

The default options are:

clearCookie: spy(), cookie: spy(), download: spy(), end: spy(), format: spy(), json: spy(), jsonp: spy(), redirect: spy(), render: spy(), send: spy(), sendFile: spy(), sendStatus: spy(), set: spy(), type: spy()

In this case most of the default functions are set to be sinon spies , so your tests can simply expect(res.end).to.have.been.calledOnce . Just like the request object, the get function is stubbed, allowing your test to control what get returns.

Both the status and vary functions are stubbed and set to return the response object, allowing chaining.

Options

Both the mockRequest and mockResponse functions return objects that include the most commonly used defaults. They can be passed an options object whose root-level values are simply merged in with those defaults, with any duplicates overwriting the defaults. So if there are specific properties of a request object you need then just pass it in as an option .

Example usage

Assume you have an ExpressJS route controller function as follows:

const save = require('../../utils/saveThing') // assume this exists. const createThing = (req, res) => { const { name, description } = req.body if (!name || !description) throw new Error('Invalid Properties') const saved = save({ name, description }) res.json(saved) }

To unit-test this you could use Mocha , Chai , Sinon , and Proxyquire as follows:

const { expect } = require('chai') const { stub, match } = require('sinon') const { mockRequest, mockResponse } = require('mock-req-res') const proxyquire = require('proxyquire') describe('src/api/things/createThing', () => { const mockSave = stub() const createThing = proxyquire('../../src/api/things/createThing', { '../../utils/saveThing': mockSave }) const res = mockResponse() const resetStubs = () => { mockSave.resetHistory() res.json.resetHistory() } context('happy path', () => { const name = 'some name' const description = 'some description' const req = mockRequest({ body: { name, description }}) const expected = { name, description, id: 1 } before(() => { save.returns(expected) createThing(req, res) }) after(resetStubs) it('called save with the right data', () => { expect(save).to.have.been.calledWith(match({ name, description })) }) it('called res.json with the right data', () => { expect(res.json).to.have.been.calledWith(match(expected)) }) }) // and also test the various unhappy path scenarios. }) Summary

Using a standard library for mocking request and response objects saves you a lot of tiresome repetition when the number of functions you have to test grows, or you find yourself writing a large collection of microservices.

The mock-req-res library is as minimal as possible, and only requires sinon as a peer dependency.

Links ExpressJS : the standard web server framework for NodeJS , Sinon : a powerful mocking library, Chai : make your tests expressive, Proxyquire : inject your own mock-objects into the modules your are testing, Mocha : a powerful test automation library, the mock-req-res library in NPM, and the mock-req-res source code in GitHub.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

tags: const,spy,res,req,The,description,your,name,mock,gt
分页:12
转载请注明
本文标题:Mocking ExpressJS Request and Response objects
本站链接:https://www.codesec.net/view/586975.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(106)