javascript 摩卡测试:未捕获的类型错误:无法读取 null 的属性“状态”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29980797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:26:09  来源:igfitidea点击:

Mocha Test: Uncaught TypeError: Cannot read property 'status' of null

javascriptnode.jsmochasuperagentexpect.js

提问by metame

Learning TDD and my first simple test for my "Hello World" server response is failing in Mocha. I'm using Mocha.js, Superagent, & Expect.js.

学习 TDD 和我对“Hello World”服务器响应的第一个简单测试在 Mocha 中失败了。我正在使用 Mocha.js、Superagent 和 Expect.js。

When I curl -i localhost:8080, I get the correct response and status code.

当 I 时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

Test code:

测试代码:

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 code:

服务器代码:

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");
});

Mocha output:

摩卡输出:

  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

I've tried googling this issue but no luck finding out what I'm doing wrong.

我试过谷歌搜索这个问题,但没有发现我做错了什么。

回答by luboskrnac

Node notation of callbacks is to have first parameter error.

回调的节点符号是第一个参数错误。

Superagent is following this Node policy. This is from superagent github site:

Superagent 遵循此 Node 策略。这是来自superagent github 站点

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
  });

So change this line

所以改变这一行

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

to

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