How to resolve "Unable to read property" should "of undefined" in chai?

I am trying to test my test against my nodejs RESTful API but keep working on the following error.

Uncaught TypeError: Cannot read property 'should' of undefined

      

I am using reify framework for my API.

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

      

Testing works fine when I remove the line res.body.should.be.a('array');

Anyway, can I fix this?

+3


source to share


1 answer


Usually, when you suspect that a value might be undefined

or null

, you should wrap the value when called should()

, for example. should(res.body)

since any property reference to null

or undefined

throws an exception.

However, Chai is using an older version should

that does not support this, so you need to confirm the value beforehand.

Add another statement instead:

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

      

Chai is using an old / deprecated version should

, so normal should(x).be.a('array')

won't work.




Alternatively, you can use the official one directly should

:

$ npm install --save-dev should

      

and use it as a replacement:

const should = require('should');

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

      

+6


source







All Articles