javascript – Mocha测试:未捕获的TypeError:无法读取null的属性“status”

前端之家收集整理的这篇文章主要介绍了javascript – Mocha测试:未捕获的TypeError:无法读取null的属性“status”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
学习TDD和我对“Hello World”服务器响应的第一个简单测试在Mocha中失败了.我正在使用Mocha.js,Superagent,& Expect.js.

当我卷曲-i localhost:8080时,我得到正确的响应和状态代码.

  1. HTTP/1.1 200 OK
  2. Content-Type: text/plain
  3. Date: Mon,27 Apr 2015 17:55:36 GMT
  4. Connection: keep-alive
  5. Transfer-Encoding: chunked
  6.  
  7. Hello World

测试代码

  1. var request = require('superagent');
  2. var expect = require('expect.js');
  3.  
  4. // Test structure
  5. describe('Suite one',function(){
  6. it("should get a response that contains World",function(done){
  7. request.get('localhost:8080').end(function(res){
  8. // TODO check that response is okay
  9. expect(res).to.exist;
  10. expect(res.status).to.equal(200);
  11. expect(res.body).to.contain('World');
  12. done();
  13. });
  14. });
  15. });

服务器代码

  1. var server = require('http').createServer(function(req,res){
  2. res.writeHead(200,{"Content-Type":"text/plain"});
  3. res.end('Hello World\n');
  4. });
  5.  
  6. server.listen(8080,function(){
  7. console.log("Server listening at port 8080");
  8. });

摩卡输出

  1. Suite one
  2. 1) should get a response that contains World
  3.  
  4.  
  5. 0 passing (110ms)
  6. 1 failing
  7.  
  8. 1) Suite one should get a response that contains World:
  9. Uncaught TypeError: Cannot read property 'status' of null
  10. at test.js:10:23
  11. at _stream_readable.js:908:16

我试过谷歌搜索这个问题,但没有运气找出我做错了什么.

解决方法

回调的节点表示法是第一个参数错误.

Superagent遵循此节点策略.这是从superagent github site

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

所以改变这一行

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

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

猜你在找的JavaScript相关文章