fco*_*tes 5 javascript json unit-testing jasmine karma-jasmine
我有一个函数,它试图将参数解析为JSON对象.如果失败,则使用后备.
解析-code.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
}
Run Code Online (Sandbox Code Playgroud)
main.js
//Some code...
parseCode('hello world!');
Run Code Online (Sandbox Code Playgroud)
我在这段代码中没有看到任何问题.但是,当我尝试为'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();
});
});
Run Code Online (Sandbox Code Playgroud)
甚至像以下一样的测试:
describe('usingJSONFallback', function() {
it('Throw an error if there is a string', function() {
var code = 'My code without JSON';
expect(usingJSONFallback(code)).toThrow();
});
});
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,测试都会失败并返回:
SyntaxError: Unable to parse JSON string
Run Code Online (Sandbox Code Playgroud)
我读到了关于使用控制异常的方法throw Error(...),但最终这并不适合我的情况.关于如何在这种情况下使用Jasmine的任何建议?
Jua*_*des 11
你不能自己调用这个函数,你必须让Jasmine通过添加一个包装函数来调用它.解释它的另一种方法是,expect当你测试它时,需要一个函数传递给它.
describe('parseCode', function() {
it('Parses a string', function() {
var code = 'My code without JSON';
expect(function() { parseCode(code) }).toThrow();
});
});
Run Code Online (Sandbox Code Playgroud)
从他们的示例页面中,注意该函数已传入但未被调用.
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");
});
Run Code Online (Sandbox Code Playgroud)
你试过包装给定的fn吗?这样jasmine就可以自己执行它并提供额外的代码来捕获它.
describe("usingJSONFallback", function() {
it("should throw an error if it's called with a string", function() {
expect(function () {
usingJSONFallback("any string");
}).toThrow();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9402 次 |
| 最近记录: |