Prz*_*mek 5 javascript unit-testing node.js express
我对表达很陌生,对单元测试也很陌生。考虑以下代码:
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;
Run Code Online (Sandbox Code Playgroud)
为此编写单元测试的正确/推荐方法是什么?例如,我希望能够测试router.route('/:id')不接受 POST 调用。
我知道我可以使用超级测试来做到这一点,但我相信这将被视为集成测试,因为超级测试将启动应用程序来运行测试。
我已经阅读并尝试了多个 node.js/express.js 测试教程,但找不到答案。非常欢迎任何指向现有教程的指示。这里直接回答,甚至更多:)
sinon.js这是使用存根express.Router函数并进行断言的单元测试解决方案。
router.js:
var express = require(\'express\');\nvar router = express.Router();\n\nvar bookingsController = require(\'./controllers/bookings\');\n\nrouter\n .route(\'/\')\n .get(bookingsController.bookings_get)\n .post(bookingsController.bookings_post);\n\nrouter\n .route(\'/:id\')\n .get(bookingsController.bookings_get_id)\n .put(bookingsController.bookings_put_id)\n .delete(bookingsController.bookings_delete_id);\n\nmodule.exports = router;\nRun Code Online (Sandbox Code Playgroud)\n\n./controller/bookings.js:
module.exports = {\n bookings_get() {},\n bookings_post() {},\n bookings_get_id() {},\n bookings_put_id() {},\n bookings_delete_id() {},\n};\nRun Code Online (Sandbox Code Playgroud)\n\nrouter.test.js:
var sinon = require(\'sinon\');\nvar express = require(\'express\');\n\ndescribe(\'61529619\', () => {\n it(\'should pass\', () => {\n const routerStub = {\n route: sinon.stub().returnsThis(),\n post: sinon.stub().returnsThis(),\n get: sinon.stub().returnsThis(),\n put: sinon.stub().returnsThis(),\n delete: sinon.stub().returnsThis(),\n };\n sinon.stub(express, \'Router\').callsFake(() => routerStub);\n require(\'./router\');\n sinon.assert.calledWith(routerStub.route, \'/\');\n sinon.assert.calledWith(routerStub.route, \'/:id\');\n sinon.assert.calledWith(routerStub.get, sinon.match.func);\n sinon.assert.calledWith(routerStub.post, sinon.match.func);\n sinon.assert.calledWith(routerStub.put, sinon.match.func);\n sinon.assert.calledWith(routerStub.delete, sinon.match.func);\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n100%覆盖率的单元测试结果:
\n\n 61529619\n \xe2\x9c\x93 should pass (869ms)\n\n\n 1 passing (881ms)\n\n----------------------|---------|----------|---------|---------|-------------------\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n----------------------|---------|----------|---------|---------|-------------------\nAll files | 100 | 100 | 0 | 100 | \n 61529619 | 100 | 100 | 100 | 100 | \n router.js | 100 | 100 | 100 | 100 | \n 61529619/controllers | 100 | 100 | 0 | 100 | \n bookings.js | 100 | 100 | 0 | 100 | \n----------------------|---------|----------|---------|---------|------------------\nRun Code Online (Sandbox Code Playgroud)\n