我正在尝试为Jasmine测试框架编写一个测试,该测试预计会出现错误。目前,我正在使用来自GitHub的Jasmine Node.js集成。

在我的Node.js模块中,我有以下代码:

throw new Error("Parsing is not possible");

现在我试着写一个测试,期望这个错误:

describe('my suite...', function() {
    [..]
    it('should not parse foo', function() {
    [..]
        expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));
    });
});

我还尝试了Error()和其他一些变体,只是不知道如何使它工作。


当前回答

it('it should fail', async () => {
    expect.assertions(1);

    try {
        await testInstance.doSomething();
    }
    catch (ex) {
        expect(ex).toBeInstanceOf(MyCustomError);
    }
});

其他回答

在我的例子中,抛出错误的函数是异步的,所以我遵循了这一点:

await expectAsync(asyncFunction()).toBeRejected();
await expectAsync(asyncFunction()).toBeRejectedWithError(...);

尝试使用匿名函数:

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

您应该向expect(…)调用传递一个函数。你的错误代码:

// incorrect:
expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));

实际上是试图调用parser.parse(raw),试图将结果传递给expect(…),

对于CoffeeScript爱好者:

expect( => someMethodCall(arg1, arg2)).toThrow()
it('it should fail', async () => {
    expect.assertions(1);

    try {
        await testInstance.doSomething();
    }
    catch (ex) {
        expect(ex).toBeInstanceOf(MyCustomError);
    }
});

我知道这是更多的代码,但你也可以这样做:

try
    Do something
    @fail Error("should send a Exception")
catch e
    expect(e.name).toBe "BLA_ERROR"
    expect(e.message).toBe 'Message'