Search code examples
javascriptnode.jsmocha.jschaiweb-api-testing

Getting undefined response to API Request through Mocha


I am unable to understand that why am I getting the undefined response to my code API request through mocha. Any leads will be appreciated Attaching the codes picture and code itself too.

import supertest from "supertest";
import { expect } from 'chai';
const request = 
    supertest("https://api.staging.graana.rocks/api/");
let a;

describe('Users', () => {
    it('GET /users', () => {
        request.get('city?home=true').end((err,res) => {
            expect(res.body.data).to.be.not.null;
            a = res.body.data;
            console.log(res.body.data);
            console.log(a)
            
        });
    });
});

Code's picture

I am really stuck any leads would be helpful. Thank You in advance.


Solution

  • Try to pass query params using the query() method.
    The test is described to call the /users end-point so you should change the .get() path accordingly if you need to test that path.

    describe('Users', () => {
      it('GET /users', async () => {
        const res = await request.get('/city').query({ home: true });
        expect(res.body.data).to.be.not.null;
        a = res.body.data;
        console.log(res.body.data);
        console.log(a);
      });
    });
    

    Also, change your supertest declaration to (remove the trailing /):

    const request = supertest("https://api.staging.graana.rocks/api");