0

I am testing a a function that is returned as a part of a promise. I'm using chai-as-promised.

I'm able to test that the function works but I am unable to test that it throws errors properly.

The function I'm trying to test, leaving out lots of code related to the promise:

// function that we're trying to test 
submitTest = (options) => {
  // missingParam is defined elsewhere. It works - the error is thrown if screenshot not passed
  if (missingParam(options.screenShot)) throw new Error('Missing parameter');

  return {};
}

My tests:

describe('SpectreClient()', function () {
  let client;

  before(() => client = SpectreClient('foo', 'bar', testEndpoint));
  // the client returns a function, submitTest(), as a part of a promise

  /* 
  omitting tests related to the client
  */

  describe('submitTest()', function () {
    let screenShot;
    before(() => {
      screenShot = fs.createReadStream(path.join(__dirname, '/support/test-card.png'));
    });

    // this test works - it passes as expected
    it('should return an object', () => {
      const submitTest = client.then((response) => {
        return response.submitTest({ screenShot });
      });
      return submitTest.should.eventually.to.be.a('object');
    });

    // this test does not work - the error is thrown before the test is evaluated
    it('it throws an error if not passed a screenshot', () => {
      const submitTest = client.then((response) => {
        return response.submitTest({});
      });

      return submitTest.should.eventually.throw(Error, /Missing parameter/);
    });       
  });
})

The output of the test -

// console output
1 failing

1) SpectreClient() submitTest() it throws an error if not passed a screenshot:
   Error: Missing parameter

How do I test that the error is thrown correclty? I'm not sure if it's a mocha problem or a promises thing or a chai-as-promised thing. Help much appreciated.

Finnnn
  • 3,530
  • 6
  • 46
  • 69

1 Answers1

0

Exceptions raised inside promise handlers are converted to promise rejections. submitTest executes inside the callback to client.then, and consequently the exception it raises becomes a promise rejection.

So you should do something like:

return submitTest.should.be.rejectedWith(Error, /Missing parameter/)
Louis
  • 146,715
  • 28
  • 274
  • 320