4

Consider a piece of code below:

var expect = require('chai').expect;

parse = function() {
  throw {error: 'PROTOCOL_ERROR'}
}

describe('parser', function() {

  it('throw error on unfinished command', function() {
    try {
      parse("*2\r\n$4\r\necho\r\n$11\r\nhel")
    } catch (e) {
      expect(e).to.equal({error: 'PROTOCOL_ERROR'})
    }
  })
});

Is there a way to avoid this try...catch boilerplate in the code? Chai has 'throw' method but it provides only an instanceof check

kharandziuk
  • 12,020
  • 17
  • 63
  • 121

2 Answers2

5

I found this answer:

var expect = require('chai').expect;

parse = function() {
  throw {error: 'PROTOCOL_ERROR'}
}

describe('parser', function() {
  it('throw error on unfinished command', function() {
      expect(
        () => parse("*2\r\n$4\r\necho\r\n$11\r\nhel")
      ).to.throw().which.has.property('error', 'PROTOCOL_ERROR');
  })
});
kharandziuk
  • 12,020
  • 17
  • 63
  • 121
0

First, you should be throwing an instance of Error or something that extends Error

parse = function() {
  throw new Error('PROTOCOL_ERROR');
}

Then chai has a method to assert that a function is throwing an error http://chaijs.com/api/bdd/#method_throw

So the final thing should look like this:

var expect = require('chai').expect;

parse = function() {
  throw new Error('PROTOCOL_ERROR');
}

describe('parser', function() {

  it('throw error on unfinished command', function() {

    expect(function() { parse("*2\r\n$4\r\necho\r\n$11\r\nhel") }).to.throw(Error, 'PROTOCOL_ERROR');

  })
});

Edit: wrapped function call in function. Otherwise the error is thrown before expect is called and has a chance to catch it.

aray12
  • 1,833
  • 1
  • 16
  • 22