2016-05-23 71 views
1

我正在嘗試爲我的API構建一個測試集,該集合是使用nodejs/express與mocha/chai一起開發的。基本上,該指數將返回一個簡單的字符串,我知道它的工作,因爲我可以在我的瀏覽器中看到:Nodejs/Express API的簡單摩卡/柴測試

router.get('/', function(req, res, next) { 
    res.send('Hello World from Eclipse'); 
}); 

然後我跟着這個tutorial建立這個測試:

var supertest = require("supertest"); 
var should = require("should"); 

// This agent refers to PORT where program is runninng. 

var server = supertest.agent("http://localhost:5000"); 

// UNIT test begin 

describe("SAMPLE unit test",function(){ 

    // #1 should return home page 

    it("should return home page",function(done){ 

    // calling home page api 
    server 
    .get("/") 
    .expect("Content-type",/json/) 
    .expect(200) // THis is HTTP response 
    .end(function(err,res){ 
     // HTTP status should be 200 
     res.status.should.equal(200); 
     // Error key should be false. 
     res.body.error.should.equal(false); 
     done(); 
    }); 
    }); 

}); 

我可以在看日誌我的服務器,地址被調用,但是,測試總是說,它不能讀取屬性'應該'的未定義,在我有'res.status.should.equal(200);'行。可能是因爲'res'是未定義的。換句話說,API沒有答案。

我在這裏錯過了什麼嗎?我跑摩卡不帶參數...

回答

1

嘗試這樣:

var expect = require('chai').expect; 
var request = require('supertest'); 
var uri = 'your url'; 

describe('Profile',function(){ 

    it('Should return a users profile',function(done){ 
     request 
      .get(uri + '/api/1.0/profile') 
      .query({app_id:'12345'}) 
      .end(function(err,res){ 

       var body = res.body; 

       expect(body.first_name).to.equal('Bob'); 
       expect(body.last_name).to.equal('Smith'); 
       done() 
      }); 
    }); 
}); 

請確保您有正確的要求包括在內。

+0

它的工作,謝謝 – Ernanirst

0

你應該.end()檢查錯誤:

.end(function(err, res) { 
    if (err) return done(err); 
    ... 
}); 

測試用例期待的內容類型相匹配/json/,它沒有,所以應該設定(和res將是不確定的,因爲那)。

+0

不,如果你是正確的,摩卡會拋出我這個錯誤,我也試圖刪除檢查JSON,同樣的錯誤。 – Ernanirst

+0

所以'err'是不確定的_and_'res'也是? – robertklep

+0

'err'是'undefined','res'不是,而是'res.body'。 – Ernanirst