I’ve been trying to test my API with jest and express. But I couldn’t figure out how to do it properly. I want to test validation while creating a user. And check what status code and response I got from the API too. But axios throws an error if API sends http 400 status code.
If I catch it and check the response from catch block I can’t seem to fail the test from try block if axios doesn’t throw the error (which means server validation failed and it returned 200 status code).
This is what I’ve tried so far
describe(`[POST] create ${ API }`, ()=>{
// check server validation with empty username
test(`using empty username while creating user.`, async ()=>{
try{
let data = { username:"", password: "1234" }
let result = await axios.post(API, data)
}catch(e){
expect(e.response.status).toEqual(400)
expect(e.response.data).toEqual(apiErrorCodes.invalidField)
}
})
})