supertest
supertest copied to clipboard
How to get an access to request object before request ?
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();
};
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 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 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.
Any updates regarding this issue?
I would also love to have this feature