Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When unit testing with Chai, what does "TypeError: Cannot read property 'address' of undefined" mean?

I keep getting this error message when unit testing using chai and none of the tests passes even though they should. What does it mean in this context? Thanks.

var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../server.js');

var should = chai.should();
var app = server.app;
var storage = server.storage;

chai.use(chaiHttp);

describe('Shopping List', function() {
  it('should list items on GET', function(done) {
chai.request(app)
  .get('/items')
  .end(function(err, res) {
    res.should.have.status(200);
    res.should.be.json; // jshint ignore:line
    res.body.should.be.a('array');
    res.body.should.have.length(3);
    res.body[0].should.be.a('object');
    res.body[0].should.have.property('id');
    res.body[0].should.have.property('name');
    res.body[0].id.should.be.a('number');
    res.body[0].name.should.be.a('string');
    res.body[0].name.should.equal('Broad beans');
    res.body[1].name.should.equal('Tomatoes');
    res.body[2].name.should.equal('Peppers');
    done();
  });
   });

Full error message:

1) Shopping List should list items on GET:
     TypeError: Cannot read property 'address' of undefined
      at serverAddress (/home/ubuntu/workspace/thinkful-node-course/unit2/node_modules/chai-http/lib/request.js:252:17)
      at new Test (/home/ubuntu/workspace/thinkful-node-course/unit2/node_modules/chai-http/lib/request.js:244:53)
      at Object.obj.(anonymous function) [as get] (/home/ubuntu/workspace/thinkful-node-course/unit2/node_modules/chai-http/lib/request.js:216:14)
      at Context.<anonymous> (test-server.js:14:8)
like image 266
iamthewalrus Avatar asked Mar 12 '23 02:03

iamthewalrus


2 Answers

Instead of using app try using:

chai.request('http://localhost:1234')
  .get('/items')
like image 97
Joakim Ericsson Avatar answered Apr 28 '23 10:04

Joakim Ericsson


The problem is the most probably with the variable app that is actually undefined, because this error is thrown in such situation, you need to check that you are correctly importing your server.js file and that it contains property app with instance of your server application.

like image 27
kubajz Avatar answered Apr 28 '23 10:04

kubajz