11

with supertest, I can make a resquest to test my node.js application

var request = require('supertest');
var api = require('../server').app;

  ...

  it('json response', function(done){

    request(api)
      .get('/api')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .end(function(err, res){
        done();
      });
  });

how I can set a specific ip to make the test request ?

  it('ip access denied', function(done){

    request(api)
      .get('/api')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      // set specific ip
      .end(function(err, res){
        res.body.message.should.eql('Access denied');
        done();
      });
  });
JuanPablo
  • 23,792
  • 39
  • 118
  • 164

3 Answers3

13

Assuming you are checking for an ip address with req.ip via express (although other frameworks will probably behave the same), set X-Forwarded-For header in your test with the required ip address:

.set('X-Forwarded-For', '192.168.2.1')

You might need to enable the trust proxy option in your server:

app.enable('trust proxy')
Michael
  • 22,196
  • 33
  • 132
  • 187
1

You can set the headers that typically contain the IP Address, Remote-Addr and X-Http-Forwarded-For. Your app is probably checking one or both of those headers to determine the IP Address.

.set('Accept', 'application/json')
.set('Remote-Addr', '192.168.2.1')
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

You can mock the ip property using jest.spyon

import { request } from "express";
// import statementts

const CLIENT_IP = '1.2.3.4';

// make a request
it('ip access denied', function(done) {
  jest.spyOn(request, 'ip', 'get').mockReturnValue(CLIENT_IP);

  request(api)
    .get('/api')
    .set('Accept', 'application/json')
    .expect('Content-Type', /json/)
    .end(function(err, res) {
      res.body.message.should.eql('Access denied');
      done();
    });
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31