I am trying to call a function from my app using supertest and sending a custom express request but I am getting a 422 Error when I send my request.
This is my custom express request
export interface CreateGroupRequest extends Request {
body: {
groupName: string;
email: string;
country: string;
};
This is my mock request
var testCreateGroupRequest: CreateGroupRequest = {
body: {
groupName: testName,
email: email,
country: 'US',
}
} as Request
This is my test so far
await supertest(app)
.post("/login")
.send(testLoginBody)
.expect(200)
.then((response) => {
sessionToken = response.body.token
}).then(() => {
supertest(app)
.post("/create_group")
.set('X-JWT-Token', `${sessionToken}`)
.send(testCreateGroupRequest)
.then((response) => {
console.log({response})
})
})
The message that is in the response is "body.groupName\" is required". How should I be creating the custom request?
CodePudding user response:
Here's one of supertest's examples:
describe('POST /users', function() {
it('responds with json', function(done) {
request(app)
.post('/users')
.send({name: 'john'})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end(function(err, res) {
if (err) return done(err);
return done();
});
});
});
Notice that in their send method, they directly send the body.
They don't extend or make their own Request.
So to fix your issue you just need to send the body and not the fake request:
supertest(app)
.post("/create_group")
.set('X-JWT-Token', `${sessionToken}`)
.send({
groupName: testName,
email: email,
country: 'US',
})
.set('Accept', 'application/json') // Don't forget the header for JSON!
.then(console.log) // Shortened
