调用mocha测试的路由

Aji*_*hik 5 routes mocha.js node.js express chai

我正在尝试使用mocha和chai编写单元测试,我面临的主要问题是,对于每个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();                              
                    });
                });
            });
Run Code Online (Sandbox Code Playgroud)

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

qba*_*ler 0

您可以为路由器对象创建一个 init 函数来填充您的路由。使用该 init 函数进行测试和实际代码。这是一个例子:

//
// 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()));
Run Code Online (Sandbox Code Playgroud)