Hi All,
I have recently started working on a Node js project and wrote some APIs. I am writing the test cases for one of the POST request but keeps getting 404 error and response body is empty.
Here's the code -
<pre>'use strict'
jest.mock('../../utils/db2.js')
const request = require('supertest')
const executeDb2Query = require('../../utils/db2.js')
const app = require('../../app')
describe('service read API test', () => {
beforeEach(() => {
jest.resetModules()
})
it('check details Good', async () => {
executeDb2Query.mockImplementation(() =>
Promise.resolve([
{
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'
}
])
)
await request(app)
.post('/api/v1/abc/xyz')
.send({
id: '090703'
})
.expect(200)
.then(res => {
console.log('Response Body :', JSON.stringify(res.body, null, 2))
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'
})
})
})
What I have tried:
Above is my code and I am getting below response as the output as the test is failing -
● Console
console.log
Response Body : [
{}
]
at __tests__/routes/details.test.js:84:17
● service read API test › check details Good
expect(received).toEqual(expected)
Expected: {"createtime": "2021-06-01 10:53:24.269686", "dnum": "090703", "enddate": "2022-05-31", "fnum": 1.049, "num": 1, "lastmodifieddate": "2021-06-02 05:34:04.382279", "rolecode": 5,"startdate": "2021-06-01"}
Received: [{}]
83 | .then(res => {
84 | console.log('Response Body :', JSON.stringify(res.body, null, 2))
> 85 | expect(res.body).toEqual({
| ^
86 | dnum: '090703',
87 | num: 1,
88 | startdate: '2021-06-01'
Any suggestion what exactly I am doing wrong here? The response body is coming as empty when it should be matching to what I have in Promise resolve.
Below is my controller code
'use strict'
const express = require('express')
const router = express.Router()
const { getDBDetails } = require('../utils/constants')
const executeDb2Query = require('../utils/db2')
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(request),
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)
}
})