2016-08-17 88 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

謝謝,我會試試看。 –