试试茉莉花

Try/catch with jasmine

本文关键字:茉莉花      更新时间:2023-09-26

我有一个函数,它试图将参数解析为JSON对象。如果失败,则使用回退。

解析代码.js

function parseCode(code) {
    try {
        usingJSONFallback(code);
    } catch() {
        usingStringFallback(code);
    }
}
function usingJSONFallback(code) {
    JSON.parse(code);
    //...more code here
}
function usingStringFallback(code) {
   //... more code here
}

main.js

//Some code...
parseCode('hello world!');

我看不到此代码中有任何问题。然而,当我试图为"catch"情况添加一些单元测试(使用Jasmine 2.3)时,Jasmine自己捕获JSON解析错误并中止测试:

例如,对于Jasmine测试,如:

describe('parseCode', function() {
    it('Parses a string', function() {
        var code = 'My code without JSON';
        expect(parseCode(code)).toThrow();
    });
});

甚至像这样的测试

describe('usingJSONFallback', function() {
   it('Throw an error if there is a string', function() {
      var code = 'My code without JSON';
      expect(usingJSONFallback(code)).toThrow();
   });
});

在这两种情况下,测试都失败并返回:

SyntaxError: Unable to parse JSON string

我读过关于使用throw Error(...)抛出受控异常的文章,但这显然不适合我的情况。关于如何在这种情况下使用Jasmine,有什么建议吗?

您不能自己调用函数,您必须让Jasmine通过添加包装器函数来调用它。另一种解释方法是,当您测试expect抛出时,它需要一个传递给它的函数。

describe('parseCode', function() {
    it('Parses a string', function() {
        var code = 'My code without JSON';
        expect(function() { parseCode(code) }).toThrow();
    });
});

从他们的示例页面中,请注意该函数已传入但未被调用。

it("The 'toThrowError' matcher is for testing a specific thrown exception", function() {
    var foo = function() {
      throw new TypeError("foo bar baz");
    };
    expect(foo).toThrowError("foo bar baz");
    expect(foo).toThrowError(/bar/);
    expect(foo).toThrowError(TypeError);
    expect(foo).toThrowError(TypeError, "foo bar baz");
  });

您是否尝试过包装给定的fn?通过这种方式,jasmine将能够自己执行它,并提供额外的代码来捕获它

describe("usingJSONFallback", function() {
    it("should throw an error if it's called with a string", function() {
        expect(function () {
            usingJSONFallback("any string");
        }).toThrow();
    });
});