Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Promise catch with Mocha

I'm trying to test the GET HTTP method from a requests module:

const get = (host, resource, options) => {
  ...
  return new Promise((resolve, reject) => fetch(url, opts)
    .then(response => {
      if (response.status >= 400) {
        reject({ 
        message: `[API request error] response status: ${response.status}`, 
        status: response.status });
      }
      resolve(response.json());
    })
    .catch(error => reject(error)));
};

And here is how I tested the .then part:

it('Wrong request should return a 400 error ', (done) => {
    let options = { <parameter>: <wrong value> };
    let errorJsonResponse = {
    message: '[API request error] response status: 400',
    status: 400,
};
let result = {};

result = get(params.hosts.api, endPoints.PRODUCTS, options);

result
  .then(function (data) {
      should.fail();
      done();
    },

    function (error) {
      expect(error).to.not.be.null;
      expect(error).to.not.be.undefined;
      expect(error).to.be.json;
      expect(error).to.be.jsonSchema(errorJsonResponse);
      done();
    }
  );
});

However I didn't find a way to test the catch part (when it gives an error and the response status is not >= 400).

Any suggestions?

It would also help me solve the problem a simple example with another code that tests the catch part of a Promise.

like image 532
rfc1484 Avatar asked Nov 09 '22 08:11

rfc1484


1 Answers

I've ended up writing the following code in order to test the catch:

it('Should return an error with invalid protocol', (done) => {
    const host = 'foo://<host>';
    const errorMessage = 'only http(s) protocols are supported';
    let result = {};

    result = get(host, endPoints.PRODUCTS);

    result
      .then(
        () => {
          should.fail();
          done();
        },

        (error) => {
          expect(error).to.not.be.null;
          expect(error).to.not.be.undefined;
          expect(error.message).to.equal(errorMessage);
          done();
        }
    );
});
like image 58
rfc1484 Avatar answered Nov 15 '22 10:11

rfc1484