Вот решение для модульного тестирования, использующее функцию sinon.js
, чтобы заглушить express.Router
и сделать утверждения.
router.js
:
var express = require('express');
var router = express.Router();
var bookingsController = require('./controllers/bookings');
router
.route('/')
.get(bookingsController.bookings_get)
.post(bookingsController.bookings_post);
router
.route('/:id')
.get(bookingsController.bookings_get_id)
.put(bookingsController.bookings_put_id)
.delete(bookingsController.bookings_delete_id);
module.exports = router;
./controller/bookings.js
:
module.exports = {
bookings_get() {},
bookings_post() {},
bookings_get_id() {},
bookings_put_id() {},
bookings_delete_id() {},
};
router.test.js
:
var sinon = require('sinon');
var express = require('express');
describe('61529619', () => {
it('should pass', () => {
const routerStub = {
route: sinon.stub().returnsThis(),
post: sinon.stub().returnsThis(),
get: sinon.stub().returnsThis(),
put: sinon.stub().returnsThis(),
delete: sinon.stub().returnsThis(),
};
sinon.stub(express, 'Router').callsFake(() => routerStub);
require('./router');
sinon.assert.calledWith(routerStub.route, '/');
sinon.assert.calledWith(routerStub.route, '/:id');
sinon.assert.calledWith(routerStub.get, sinon.match.func);
sinon.assert.calledWith(routerStub.post, sinon.match.func);
sinon.assert.calledWith(routerStub.put, sinon.match.func);
sinon.assert.calledWith(routerStub.delete, sinon.match.func);
});
});
Результаты модульных испытаний со 100% покрытием:
61529619
✓ should pass (869ms)
1 passing (881ms)
----------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 0 | 100 |
61529619 | 100 | 100 | 100 | 100 |
router.js | 100 | 100 | 100 | 100 |
61529619/controllers | 100 | 100 | 0 | 100 |
bookings.js | 100 | 100 | 0 | 100 |
----------------------|---------|----------|---------|---------|------------------