5

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.

rfc1484
  • 9,441
  • 16
  • 72
  • 123
  • 1
    You can catch an exception with invalid protocol in url, for instance. Though it would be more effective to stub `fetch` for the spec. Btw the code is promise constructor antipattern, it may be just `return fetch(...).then(...).catch(...)`. – Estus Flask Sep 26 '16 at 16:22

1 Answers1

1

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();
        }
    );
});
rfc1484
  • 9,441
  • 16
  • 72
  • 123
  • 3
    If any of the assertions fail (they throw an error), you'll run into problems with this setup. See [this answer](http://stackoverflow.com/a/39718611/893780) I posted earlier today. – robertklep Sep 27 '16 at 11:36
  • If the assertions fail the test should break, I don't see a problem with that. Anyways I think your approach explained in the linked answer seems a better way to do it. – rfc1484 Sep 27 '16 at 14:58
  • 3
    What my answer is trying to say is that if the assertions fail, the test might not break as expected. – robertklep Sep 27 '16 at 15:00