supertest icon indicating copy to clipboard operation
supertest copied to clipboard

How to get an access to request object before request ?

Open golubvladimir opened this issue 4 years ago • 6 comments

Without supertest:

  it('success', () => {
    const req = {
      user: {
        name: 'Jack',
        type: 'admin'
      }
    };

    const next = jest.fn();

    authenticateAdmin(req, {}, next);

    expect(next).toBeCalled();
  });

With jest

  beforeEach(() => {
    const app = express();

    app.post(
      '/',
      authenticateAdmin,
      () => {}
    );
  });

  it('success', () => {
    request(app)
      .post('/')
      .send({
        user: {
          name: 'Jack',
          type: 'admin'
        }
      })
  });

But with send, I send body object. How to set an object property of request ?

I want to test it:

module.exports = (req, res, next) =>  {
  const user = req.user;

  console.log({ req });

  if (user.type !== 'admin') {
    return res.status(403).json({ error: req.t('errors.auth.access_error') });
  }

  next();
};

golubvladimir avatar Mar 13 '20 09:03 golubvladimir

  beforeEach(() => {
    const user = {
      name: 'Jack',
      type: 'admin'
    };

    app.post(
      '/',
      [
        (req, res, next) => {
          req.user = user;
          next();
        },
        authenticateAdmin
      ],
      (req, res) => {
        res.status(200).json({ result: true });
      }
    );
  });

  it('success', (done) => {
    request(app)
      .post('/')
      .end((err, res) => {
        if (err) return done(err);

        console.log(res.body.result);

        done();
      });
  });

golubvladimir avatar Mar 13 '20 10:03 golubvladimir

@golubvladimir All supertest will do is to create an http request. If req.user is result of some form on authentication mechanism, you have to replicate (at http level) whatever that mechanism requires to complete the authentication process.

jonathansamines avatar Mar 14 '20 00:03 jonathansamines

@jonathansamines How do we access the request before it's sent? I'm trying to debug whether my request is actually being made or not, as I don't seem to be getting any response at all, so I want to first confirm that the request has been built properly, then somehow confirm that it has been sent.

Corinos avatar Mar 31 '20 11:03 Corinos

Any updates regarding this issue?

benjaminhera avatar Jul 27 '23 11:07 benjaminhera

I would also love to have this feature

chtpl avatar Jan 26 '24 14:01 chtpl