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?
CodePudding user response:
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.