- JasmineJS 教程
- JasmineJS - 首页
- JasmineJS - 概述
- JasmineJS - 环境设置
- JasmineJS - 书写测试 & 执行
- JasmineJS - BDD 架构
- JasmineJS - 测试的构建块
- JasmineJS - 断言
- JasmineJS - 跳过块
- JasmineJS - 等值检查
- JasmineJS - 布尔值检查
- JasmineJS - 顺序检查
- JasmineJS - 空值检查
- JasmineJS - 不等值检查
- JasmineJS - 非数字检查
- JasmineJS - 异常检查
- JasmineJS - beforeEach()
- JasmineJS - afterEach()
- JasmineJS - 间谍 (Spies)
- JasmineJS 有用资源
- JasmineJS - 快速指南
- JasmineJS - 有用资源
- JasmineJS - 讨论
JasmineJS - 异常检查
除了不同的计算匹配器之外,Jasmine 还提供了一些有用的匹配器来检查程序的异常。让我们用以下代码修改我们的 JavaScript 代码。
var throwMeAnError = function() {
throw new Error();
};
describe("Different Methods of Expect Block", function() {
var exp = 25;
it ("Hey this will throw an Error ", function() {
expect(throwMeAnError).toThrow();
});
});
在上面的例子中,我们创建了一个方法,该方法故意从该方法中抛出一个异常,并且在 expect 块中,我们期望捕获该错误。如果一切顺利,这段代码将产生以下输出。
现在,为了使这个测试用例失败,我们需要省略函数 **throwMeAnError** 中的 throw 语句。以下是将产生红色截图作为输出的代码,因为代码不满足我们的要求。
var throwMeAnError = function() {
//throw new Error();
};
describe("Different Methods of Expect Block",function() {
var exp = 25;
it("Hey this will throw an Error ", function() {
expect(throwMeAnError).toThrow();
});
});
可以看到,我们已经注释掉了我们的方法抛出异常的那一行。以下是上述代码在 SpecRunner.html 成功执行后的输出。
Jasmine.Any()
**Any** 是一个特殊的匹配器,当我们不确定输出时使用。在下面的例子中,我们将学习它是如何工作的。让我们用以下代码修改 **customerMatcher.js**。
var addAny = function() {
var sum = this.currentVal;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
this.currentVal = sum;
return this.currentVal;
}
describe("Different Methods of Expect Block",function () {
it("Example of any()", function() {
expect(addAny(9,9)).toEqual(jasmine.any(Number));
});
});
在这里,我们声明了一个函数,它将给出作为参数提供的数字的总和。在 expect 块中,我们期望结果可以是任何值,但它应该是一个数字。
由于 9 和 9 相加的结果 18 是一个数字,所以这个测试将通过,并且它将生成以下绿色截图作为输出。
现在让我们根据以下代码更改代码,在这里我们期望一个字符串类型的变量作为函数 **AddAny()** 的输出。
var addAny = function() {
var sum = this.currentVal;
for(var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
this.currentVal = sum;
return this.currentVal;
}
describe("Different Methodsof Expect Block",function () {
it("Example of any()", function () {
expect(addAny(9,9)).toEqual(jasmine.any(String));
});
});
以下是上述代码的输出。
广告