javascriptnode.jsmocha.js

Mocha not print result in console after api hit


Here is my mocha script. I am hitting an api and in that api, i will send the result. I need to print the results obtained. While i print it, it is always saying as undefined. How can i do this.

var assert = require('assert');
console.log('Starting Test...')
describe('api', function() {
  describe('GET /getStore', function(data) {
    it('respond with an array of users', function() {
      console.log(data);
    });
  });
});

Solution

  • As i have Informed earlier on the comment section

    You can do a simple try.. catch to do this. Based on response you can handle in your code.

    You should definitely use any http library to hit the api and get the resonse. (You can prefer node-fetch , axios or any available lib)

    const assert = require('assert');
    const fetch = require('node-fetch');
    const BASE_URL = 'http://localhost:3000';
    
    describe('API - Get Store Endpoint', function() {
      
      it('should fetch the list of users in array', async function() {
        try {
          const response = await fetch(`${BASE_URL}/getStore`); // You can replace it with the actual API URL
          const users = await response.json();
    
          console.log('Received Users:', users);
    
          // Below is the basic check to ensure that we got an array in the response
          assert.strictEqual(Array.isArray(users), true, 'Expected response to be an array');
          
        } catch (error) {
          console.error('API call failed:', error.message);
          assert.fail('Failed to fetch data from /getStore');
        }
      });
    
    });
    
    

    Additionally

    If you have more endpoints for some more test case then you can even build them like:

    const GET_STORE_URL = `${BASE_URL}/getStore`;
    

    Arrow functions are also supported

      it('should fetch the list of users in array', async () => {...})