Click here to Skip to main content
15,667,847 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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'

const request = require('supertest')
const executeDb2Query = require('../../utils/db2.js')
const app = require('../../app')

describe('service read API test', () => {
  beforeEach(() => {
  it('check details Good', async () => {
    executeDb2Query.mockImplementation(() =>
          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)
        id: '090703'
      // .expect('Content-Type', /json/)
      .then(res => {
        console.log('Response Body :', JSON.stringify(res.body, null, 2))
          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

      Response Body : [

      at __tests__/routes/details.test.js:84:17

  ● service read API test › check details Good

    expect(received).toEqual(expected) // deep equality

    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')'/', 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
        .json({ message: 'No Records found for the given attributes' })
  } catch (error) {
    return next(error)
Updated 15-Nov-21 23:05pm
Chris Copeland 15-Nov-21 11:47am    
This sounds more like the API isn't producing the output that you expect, rather than an issue with this piece of code in particular. You might need to look at the documentation for the API endpoint and see why it's producing an incompatible response.

Your code is expecting a JSON object back with properties such as 'dnum', 'num' but you can clearly see the actual response out is a JSON array of objects.
Neil3092 15-Nov-21 12:07pm    
Hey Chris - I have updated the response body and get the result as shown above. And what exactly am I supposed to look in the documentation of the API? I have written the API and it gets a request body and based on that, it gives out the response in the format shown above.
Chris Copeland 15-Nov-21 12:18pm    
You'll need to amend either the API endpoint to correctly produce the result you're expecting (we can't see this code, you haven't included it, you can always edit your original question by using the Improve Question button) or amend your Javascript to correctly consume the data.

As I said, your Javascript is expecting a JSON object in the response body, but you can see from the console.log() line that it's producing a JSON array instead. Either your Javascript is wrong or the result returned from the API endpoint is wrong, you need to assess which is the correct result.
Neil3092 15-Nov-21 12:25pm    
I have added the controller code and in the res.body, I added [] across the res.body. I believe I am expecting the results in JSON array format. How do I change the JSON Object to JSOn Array instead?

1 solution

If the request response is producing an array of objects (which it likely will be given the controller code and the output from the console.log) then you simply need to iterate over the response body just like any other array.

for (let i = 0; i < res.body.length; i++) {
  const record = res.body[i];

Just be aware as well that the object that got printed was also empty, so it has no properties which is a different issue altogether. If the object doesn't contain any properties then the controller code might be producing an invalid output as well, perhaps add some logging or debug the controller and see what the values in the getDetails variable are.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900