Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Express req.ip returning object

I have an express app:

const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors({ optionsSuccessStatus: 200 }));
app.get('/api/whoami', (req, res) => {
    const ipaddress = req.ip;
    res.status(200).json({ ipaddress });
});
    
app.listen(process.env.PORT || 3000);    
module.exports = app;

and a test file:

const chai = require('chai');

const chaiHttp = require('chai-http');
const chaiMatch = require('chai-match');
const { describe, it } = require('mocha');
const server = require('../../server');

const should = chai.should();
const { expect } = chai;
chai.use(chaiHttp);
chai.use(chaiMatch);

describe('/GET /api/whoami', () => {
  it('should return the IP address', (done) => {
    chai.request(server)
      .get('/api/whoami')
      .end((err, res) => {
        res.should.have.status(200);
        res.body.should.be.a('object');
        res.body.should.have.property('ipaddress');
        expect(res.body.ipaddress).should.match(/* very long regex */);
        done();
      });
  });
});

for some reason, I keep geting Uncaught AssertionError: expected Assertion{ __flags: { …(4) } } to match [my very long regex], i didn’t find anyone with the same error. How can I get my true ip with express? Or what is the right way to test it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The syntax is expect(something).to.match and not expect(something).should.match. See docs. Or, if you want to use should, you don’t need expect, since the syntax for that is something.should.match.

The fix is therefore to change your code either as follows:

expect(res.body.ipaddress).to.match(/* very long regex */);

…or as follows:

res.body.ipaddress.should.match(/* very long regex */);

In the style guide, you get a good comparison between how to use expect and how to use should.

By mixing those two things, you took expect(...) which returns object that contains things like to and used it as source of your should, so that should.match check operated on the object returned by expect(...) and not the IP address itself.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading