0

In Junit testing I can expect an exception to be thrown in the test like this :

@Test(expect=SomeExceptino.class)
public void shouldThrowException(){
//test goes here.

}

How can I do this with JS and Jasmine ?

I have Something like:

function ActionDispatcher() {

    var actionHandlers = {};

    this.dispatch = function (action) {
        var actionHandler = actionHandlers[action.constructor];

        if (actionHandler == undefined) {
            throw new Error('not handler for action:' + action.constructor);
        } else {
            actionHandler.handle(action);
        }
    };
    }

How do I write test that expects dispatch to throw exception?

I am spying on action Hanlders not the tested ActionDipatcher. I think it is ridiculous to spy on the object you are testing.

Adelin
  • 18,144
  • 26
  • 115
  • 175

1 Answers1

1

Jasmine has a toThrow matcher that allows you to test for exceptions. You can use it like so:

it("throws", function() {
  var dispatcher = new ActionDispatcher();
  expect(function() {
    dispatcher.dispatch({constructor: 'constructor'});
  }).toThrow(new Error('not handler for action: constructor'));
});
Gregg
  • 2,628
  • 1
  • 22
  • 27