【问题标题】:Cannot read property 'status' of undefined - Mocha Chai无法读取未定义的属性“状态” - Mocha Chai
【发布时间】:2020-01-12 16:02:35
【问题描述】:

所以我是 nodejs 环境中 mocha-chai 的新手。 我不明白为什么我在运行 mochajs 时无法获得响应状态。

这是我的代码:

let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('server');
let expect = require("chai").expect;
let should = require("should");

let request = require("superagent");
let util = require("util");

chai.use(chaiHttp);

describe('API Clinic Test', function() {

  it('should list ALL clinic on /api/v1/clinic GET', function(done) {
  chai.request(server)
    .get('http://localhost:5000/api/v1/clinic')
    .end(function(err, res){
        // res.should.have.status(200);
        expect(res.status).to.equal(200);
      done();
    });
  });

  it('should list a SINGLE clinic on /api/v1/clinic/<id> GET');
  it('should add a SINGLE clinic on /api/v1/clinic POST');
  it('should update a SINGLE clinic on /api/v1/clinic/<id> PUT');
  it('should delete a SINGLE clinic on /api/v1/clinic/<id> DELETE');
});

每次我运行 mocha test.js,我总是得到这个错误消息:

未捕获的类型错误:无法读取未定义的属性“状态”

ohya,我也使用 should 方法。 我收到了另一个错误消息,例如:无法读取属性应该为空

我读过这个线程。

Should js Cannot read property 'should' of null

这就是我想改变和使用期望方法的原因。

你们能帮帮我吗。

谢谢。

::: 更新 ::: 如何解决这个问题? 而不是使用这行代码:

it('should list ALL clinic on /api/v1/clinic GET', function(done) {
  chai.request(server)
    .get('http://localhost:5000/api/v1/clinic')
    .end(function(err, res){
        // res.should.have.status(200);
        expect(res.status).to.equal(200);
      done();
    });
  });

我用这个:

it('should list ALL clinic on /api/v1/clinic GET', function(done) {
chai.request('localhost:5000') .get('/api/v1/clinic') 
.end(function(err, res){
            // res.should.have.status(200);
            expect(res.status).to.equal(200);
          done();
        });
      });

【问题讨论】:

  • 这只是意味着您的res 对象未定义,因此它没有任何属性,包括status - 即您的结果不会返回。你能从命令行向你的目标发出一个简单的 GET 并确认它以 200 响应吗?

标签: javascript node.js mocha.js chai


【解决方案1】:

您最有可能遇到错误...您应该有类似于下面的行

if(err) done(err);

每厘米...这引导您朝着正确的方向前进。此外,您需要执行以下操作:

chai.request('http://localhost:5000').get('/api/v1/clinic')

【讨论】:

  • 在您的 .end() 回调中...几乎在您的注释行所在的位置。在该块中使用 if/else 也不是一个坏主意。为了进一步调试,您可以通过使用 try/catch 包装来确保它不是其他错误
  • 我不明白。我按照你的指示,得到另一个错误消息。错误:连接 ECONNREFUSED 127.0.0.1:80
  • 想我会添加更多。格式化的方式,您不需要指定 localhost url,只需指定端点,因为您使用 express 应用程序提供 chai.request。所以,我应该看起来像 chai.request(server).get('/api/v1/clinic')
  • 或者...你可能想做类似chai.request('http://localhost:5000').get('/api/v1/clinic')
  • 运气好吗?如果是这样,我将编辑我的回复,以便您标记答案?
【解决方案2】:

在我的情况下,我忘记导出像 export defaul mymodule 这样的模块。所以检查一下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2021-11-28
    • 2019-07-25
    • 2020-11-05
    • 2021-07-07
    相关资源
    最近更新 更多