How to get mocha to use http response?

Member

by mac , in category: Javascript , 7 days ago

How to get mocha to use http response?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 6 days ago

@mac 

To get Mocha to use an HTTP response, you can use a library like supertest or axios to make HTTP requests within your test cases. Here is an example using supertest:

  1. First, install supertest using npm:
1
npm install supertest --save-dev


  1. In your test file, import supertest and the app you want to test (assuming you have an Express app):
1
2
const request = require('supertest');
const app = require('../app');


  1. Write your test case using supertest to make an HTTP request and assert on the response:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
describe('GET /', () => {
  it('responds with status code 200', (done) => {
    request(app)
      .get('/')
      .expect(200)
      .end((err, res) => {
        if (err) return done(err);
        done();
      });
  });
});


  1. Run your Mocha test file using the Mocha command line or through your test runner of choice.


By using supertest or a similar library, you can test your HTTP endpoints within your Mocha test suites and assert on the responses.