2015-05-01 38 views
7

學習TDD和我的「Hello World」服務器響應的第一個簡單測試在Mocha中失敗。我正在使用Mocha.js,Superagent,& Expect.js。摩卡測試:未捕獲TypeError:無法讀取null的屬性'狀態'

當我curl -i localhost:8080,我得到正確的響應和狀態代碼。

HTTP/1.1 200 OK 
Content-Type: text/plain 
Date: Mon, 27 Apr 2015 17:55:36 GMT 
Connection: keep-alive 
Transfer-Encoding: chunked 

Hello World 

測試代碼:

var request = require('superagent'); 
var expect = require('expect.js'); 

// Test structure 
describe('Suite one', function(){ 
    it("should get a response that contains World",function(done){ 
     request.get('localhost:8080').end(function(res){ 
      // TODO check that response is okay 
      expect(res).to.exist; 
      expect(res.status).to.equal(200); 
      expect(res.body).to.contain('World'); 
      done(); 
     }); 
    }); 
}); 

Server代碼:

var server = require('http').createServer(function(req, res){ 
    res.writeHead(200, {"Content-Type":"text/plain"}); 
    res.end('Hello World\n'); 
}); 

server.listen(8080, function(){ 
    console.log("Server listening at port 8080"); 
}); 

摩卡輸出:

Suite one 
    1) should get a response that contains World 


    0 passing (110ms) 
    1 failing 

    1) Suite one should get a response that contains World: 
    Uncaught TypeError: Cannot read property 'status' of null 
     at test.js:10:23 
     at _stream_readable.js:908:16 

我試着用搜索引擎這個問題,但沒有運氣找到了什麼我做錯了。

+0

是否有人注意到期待()to.equal不工作了???而圖書館的作者沒有提到這個垃圾?順便說一句,它從「.to.equal」改爲「toEqual」。我很驚訝這傢伙的代碼可以工作 – enorl76

回答

10

回調的節點標記是第一個參數錯誤。

Superagent遵循此節點策略。這是superagent github site

request 
    .post('/api/pet') 
    .send({ name: 'Manny', species: 'cat' }) 
    .set('X-API-Key', 'foobar') 
    .set('Accept', 'application/json') 
    .end(function(err, res){ 
    // Calling the end function will send the request 
    }); 

所以這條線

request.get('localhost:8080').end(function(res){ 

改變

request.get('localhost:8080').end(function(err, res){ 
+0

這就是問題@lkrnac - 測試正在工作。 – metame

相關問題