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

前端 未结 9 1109
忘了有多久
忘了有多久 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:06

    As mentioned previously, a function needs to be passed to toThrow as it is the function you're describing in your test: "I expect this function to throw x"

    expect(() => parser.parse(raw))
      .toThrow(new Error('Parsing is not possible'));
    

    If using Jasmine-Matchers you can also use one of the following when they suit the situation;

    // I just want to know that an error was
    // thrown and nothing more about it
    expect(() => parser.parse(raw))
      .toThrowAnyError();
    

    or

    // I just want to know that an error of 
    // a given type was thrown and nothing more
    expect(() => parser.parse(raw))
      .toThrowErrorOfType(TypeError);
    

提交回复
热议问题