调用路线进行摩卡testing

我正在尝试使用摩卡和柴编写unit testing,我面临的主要问题是,对于每个API我必须明确定义的url,即

test.js

var expect = require('chai').expect; var should = require('chai').should; var express = require('express'); var chai = require('chai'); var chaiHttp = require('chai-http'); chai.use(chaiHttp); var baseUrl = 'http://localhost:3000/api'; describe("Test case for getting all the users", function(){ it("Running test", function(done){ this.timeout(10000); //to check if the API is taking too much time to return the response. var url = baseUrl + '/v1/users?access_token=fd085c73227b94fb3d1d5552b5a62be963b6d068' chai.request(url) .get('') .end(function(err, res) { //console.log('routes>>>>', routes); expect(err).to.be.null; expect(res.statusCode).to.equal(200); // <= Call done to signal callback end expect(res).to.have.property('text'); done(); }); }); }); 

我希望我所有的路由都能直接从我的routes.js文件中调用,而不是硬编码每一个url, 这有可能吗? TIA。

您可以为路由器对象创build一个init函数来填充路由。 使用这个init函数来testing和实际的代码。 这里是一个例子:

 // // initRouter.js // function initRouter(router){ router.route('/posts') .post(function(req, res) { console.log('req.body:', req.body) //Api code }); router.route('/posts/:post_id') .get(function(req, res) { console.log('req.body:', req.body) //Api code }) return router; } module.exports = initRouter; // // in the consumer code // var initer = require('./initRouter'); app.use('/api', initer(express.Router())); 

在这个示例中,您正在testing通过某个IP和PORT公开的现有Web服务器。 使用express-mocks-http可以模拟表示请求和响应对象,并将它们直接传递给您定义的路由函数。 有关更多信息,请参阅包文档。