How to write a test which expects an Error to be thrown in Jasmine?

前端 未结 9 1098
忘了有多久
忘了有多久 2020-11-28 17:26

I\'m trying to write a test for the Jasmine Test Framework which expects an error. At the moment I\'m using a Jasmine Node.js integration from GitHub.

In my Node mod

9条回答
  •  被撕碎了的回忆
    2020-11-28 18:15

    A more elegant solution than creating an anonymous function who's sole purpose is to wrap another, is to use es5's bind function. The bind function creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

    Instead of:

    expect(function () { parser.parse(raw, config); } ).toThrow("Parsing is not possible");

    Consider:

    expect(parser.parse.bind(parser, raw, config)).toThrow("Parsing is not possible");

    The bind syntax allows you to test functions with different this values, and in my opinion makes the test more readable. See also: https://stackoverflow.com/a/13233194/1248889

提交回复
热议问题