Test error flows using your favorite test framework

One Paragraph Explainer

Testing ‘happy’ paths is no better than testing failures. Good testing code coverage demands to test exceptional paths. Otherwise, there is no trust that exceptions are indeed handled correctly. Every unit testing framework, like Mocha & Chai, supports exception testing (code examples below). If you find it tedious to test every inner function and exception you may settle with testing only REST API HTTP errors.

Code example: ensuring the right exception is thrown using Mocha & Chai

Javascript

  1. describe('Facebook chat', () => {
  2. it('Notifies on new chat message', () => {
  3. const chatService = new chatService();
  4. chatService.participants = getDisconnectedParticipants();
  5. expect(chatService.sendMessage.bind({ message: 'Hi' })).to.throw(ConnectionError);
  6. });
  7. });

Typescript

  1. describe('Facebook chat', () => {
  2. it('Notifies on new chat message', () => {
  3. const chatService = new chatService();
  4. chatService.participants = getDisconnectedParticipants();
  5. expect(chatService.sendMessage.bind({ message: 'Hi' })).to.throw(ConnectionError);
  6. });
  7. });

Code example: ensuring API returns the right HTTP error code

Javascript

  1. it('Creates new Facebook group', () => {
  2. const invalidGroupInfo = {};
  3. return httpRequest({
  4. method: 'POST',
  5. uri: 'facebook.com/api/groups',
  6. resolveWithFullResponse: true,
  7. body: invalidGroupInfo,
  8. json: true
  9. }).then((response) => {
  10. expect.fail('if we were to execute the code in this block, no error was thrown in the operation above')
  11. }).catch((response) => {
  12. expect(400).to.equal(response.statusCode);
  13. });
  14. });

Typescript

  1. it('Creates new Facebook group', async () => {
  2. let invalidGroupInfo = {};
  3. try {
  4. const response = await httpRequest({
  5. method: 'POST',
  6. uri: 'facebook.com/api/groups',
  7. resolveWithFullResponse: true,
  8. body: invalidGroupInfo,
  9. json: true
  10. })
  11. // if we were to execute the code in this block, no error was thrown in the operation above
  12. expect.fail('The request should have failed')
  13. } catch(response) {
  14. expect(400).to.equal(response.statusCode);
  15. }
  16. });