2016-08-17 89 views
5

我试图用摩卡和薛宝钗,我面对整个大问题编写单元测试是每一个原料药我有专门定义的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。

回答

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())); 
0

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

+0

谢谢,我会试试看。 –