用Sinon / Mocha正确的剔除请求/响应
我对后端的unit testing相对比较陌生,需要一些关于如何对以下内容进行unit testing的指导。 我正在使用Mocha / Should / Sinon。
exports.get = function(req, res) { if (req.query.example) { return res.status(200).json({ success: true }); } else { return res.status(400).json({error: true}); } }
你可以使用Sinon的spy
和stub
function来testing你的代码:
const { spy, stub } = require('sinon'); const chai = require('chai'); chai.should(); describe('the get function', () => { let status, json, res; beforeEach(() => { status = stub(); json = spy(); res = { json, status }; status.returns(res); }); describe('if called with a request that has an example query', () => { beforeEach(() => get({ query: { example: true } }, res)); it('calls status with code 200', () => status.calledWith(200).should.be.ok ); it('calls json with success: true', () => json.calledWith({ success: true }).should.be.ok ); }); describe('if called with a request that doesn\'t have an example query', () => { beforeEach(() => get({ query: {} }, res)); it('calls status with code 400', () => status.calledWith(400).should.be.ok ); it('calls json with error: true', () => json.calledWith({ error: true }).should.be.ok ); }); });
在第一个beforeEach
调用中,我创build了一个名为status
的存根和一个名为json
的间谍。
status
存根用于testing是否用正确的响应代码调用响应的状态方法。
json
间谍用于testing是否用正确的JSON代码调用响应的json方法。
注意我正在使用存根status
能够从任何调用status
方法返回模拟响应,否则链( res.status().json()
)将无法正常工作。
对于json
来说,使用简单的间谍就足够了,因为它在链的末尾。