I am currently working on a node js app where I wrote one of the API using a POST request to fetch the data from the DB. I have used POST req as I didn't want to expose the params in the URL and sending the where clause in the request body of a post request.
I am currently writing the test cases using jest for the post API but getting a bad request error. Here's my code -
'use strict'
jest.mock('../../utils/db2.js')
const request = require('supertest')
const app = require('../../app')
describe('service read API test', () => {
beforeEach(() => {
jest.resetModules()
})
it('service read API good', async () => {
const res = await request(app)
.post('/api/v1/abc/xyz/')
.send({
id: '090703'
})
console.log('Response Body :', JSON.stringify(res.body, null, 2))
expect(res.status).toBe(200)
expect(res.body).toEqual({
dnum: '090703',
num: 1,
startdate: '2021-06-01',
enddate: '2022-05-31',
rolecode: 5,
fnum: 1.049,
lastmodifieddate: '2021-06-02 05:34:04.382279',
createtime: '2021-06-01 10:53:24.269686',
})
})
Basically in the API, in the request body, I am sending id and in the response body, I get the result set based on the id provided. But I keep getting below error -
● Console
console.log
Response Body : {
"message": "No Records found for the given attributes"
}
service read API test › service read API good
expect(received).toBe(expected) // Object.is equality
Expected: 200
Received: 400
46 | })
47 | console.log('Response Body :', JSON.stringify(res.body, null, 2))
> 48 | expect(res.status).toBe(200)
| ^
49 | expect(res.body).toEqual({
50 | dnum: '090703',
51 | num: 1,
I have tried various things but not sure what am I doing wrong here. Any suggestion?
Controller code below -
'use strict'
const express = require('express')
const router = express.Router()
const { getDBDetails } = require('../utils/constants')
const executeDb2Query = require('../utils/db2')
const { validate } = require('express-validation')
router.post('/', async (req, res, next) => {
try {
if (req.body.constructor === Object && Object.keys(req.body).length === 0) {
return res.status(400).send('Request Body is empty. Please check!!')
}
const request= req.body
const getDetails = await executeDb2Query({
sql: getDBDetails(disNum),
log: req.log,
name: 'Get Details',
errorMsg: 'Get error while getting the Details '
})
return res.status(200).json(getDetails)
} else {
return res
.status(400)
.json({ message: 'No Records found for the given attributes' })
}
} catch (error) {
return next(error)
}
})