set ip in supertest request
Asked Answered
V

3

12

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();
      });
  });
Vargo answered 18/12, 2014 at 18:37 Comment(0)
B
14

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')
Brucine answered 4/1, 2016 at 8:58 Comment(0)
S
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')
Saleh answered 18/12, 2014 at 18:42 Comment(0)
C
1

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();
    });
});
Capful answered 7/3, 2023 at 2:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.