【问题标题】:How to resolve "Cannot read property 'should' of undefined" in chai?如何解决柴中的“无法读取属性'应该'未定义”?
【发布时间】:2017-05-15 08:50:41
【问题描述】:

我正在尝试测试我的 RESTful nodejs API,但一直遇到以下错误。

Uncaught TypeError: Cannot read property 'should' of undefined

我正在为我的 API 使用 restify 框架。

'use strict';

const mongoose = require('mongoose');
const Customer = require('../src/models/customerSchema');

const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../src/app');
const should = chai.should();

chai.use(chaiHttp);

describe('Customers', () => {
   describe('/getCustomers', () => {
       it('it should GET all the customers', (done) => {
           chai.request(server)
               .get('/getCustomers')
               .end((err, res) => {
                   res.should.have.status(200);
                   res.body.should.be.a('array');
                   done();
                });
       });
   });
});

当我删除res.body.should.be.a('array'); 行时,测试工作正常 无论如何我可以解决这个问题吗?

【问题讨论】:

    标签: node.js mocha.js chai


    【解决方案1】:

    通常,当您怀疑某个值可能是 undefinednull 时,您会将该值包装在对 should() 的调用中,例如should(res.body),因为引用 nullundefined 上的任何属性都会导致异常。

    但是,Chai 使用的是不支持此功能的旧版本 should,因此您需要事先声明该值的存在。

    相反,再添加一个断言:

    should.exist(res.body);
    res.body.should.be.a('array');
    

    Chai 使用的是旧版本/过时版本的 should,因此通常的 should(x).be.a('array') 将无法使用。


    也可以直接使用官方的should包:

    $ npm install --save-dev should
    

    并将其用作替代品:

    const should = require('should');
    
    should(res.body).be.a('array');
    

    【讨论】:

    • 现在我收到了错误Uncaught TypeError: should is not a function
    • const should = chai.should(); 更改为const should = chai.should;
    • 我按照你说的改了线路,但现在我收到了Uncaught TypeError: Cannot read property 'have' of undefined。我的代码是res.should.have.status(200); should(res.body).be.a('array');
    • @BattleFrog Chai 使用了should 的精简版。查看我更新的答案(忽略我的最后评论 - 保留括号,您确实需要它们)。
    • chai.should().exist(...).should.work (doc)
    猜你喜欢
    • 2019-04-30
    • 2021-05-10
    • 2022-01-26
    • 2019-11-21
    • 2020-06-20
    • 2018-12-21
    • 2020-11-17
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多