





















2012-11-14 16:20 Zhuang miao 阅读(2618) 评论() 收藏 举报
上一篇:使用Jasmine测试你的Javascript(一)之 Jasmine简介 我们初步了解jasmine可以做什么。
接下来我们开始进一步的了解Jasmine,让我们熟悉一下Jasmine测试用列的基本语法结构。
每个spec都是一个Javascript函数,在这里可以认为就是一个测试的主体,specs用jasmine的全局方法it() 来定义,它包含了两个参数,一个string,一个function,string用来描述spec的行为,它应该是有意义的,这样以便于你在之后阅读你的测试报告 .如下代码定义了一个Spec。
it('Student must defined', function () { var foo = 0; foo++;
});
Expectations在jasmine就相当于一个断言,在一个spec中你将使用它来断言你的代码表达式是否成立,expectations使用 expect() 方法定义。在一个spec中,只有当所有的expectations全被为true时,该spec才显示为通过,否则该spec失败。
it('should increment a variable', function () { var foo = 0;
foo++;
expect(foo).toEqual(1);
});
当你运行spec之后,该expectation的结果将会反馈给你,反馈的结果将会类似如下这样。你也可以通过本文上方红色链接进入jasmine的在线尝试。
1 spec, 0 failures in 0.277sFinished at Wed Nov 14 2012 15:01:40 GMT+0800 (China Standard Time)
多个Specs被组织在Suites中.,相当于specs的合集Suites 使用全局方法describe()定义,它包含两个参数,一个string,一个function,string用来描述该suite,也请确保它是有意义的,因为它将在运行结束的报告中显示以助于你分析相应Cases, 而function中的内容就是suites的合集。
describe('Calculator', function () {it('can add a number', function () {
... }); it('can multiply some numbers', function () { ... }); });
一个suite中的specs共享同一个函数作用域,所以你在一个suite中声明的变量可以被所有specs访问,代码如下
describe('Calculator', function () { var counter = 0 it('can add a number', function () { counter = counter + 2; // counter was 0 before expect(counter).toEqual(2); }); it('can multiply a number', function () { counter = counter * 5; // counter was 2 before expect(counter).toEqual(10); }); });
注意上面的代码只在describe( )函数上执行一次,这就是为什么counter没有重置为0。如果你想在第二个spec(can multiply a number)中将counter重置,请使用beforeEach( )函数。
Jasmine支持嵌套describes.代码如下
describe('some suite', function () { var suiteWideFoo; beforeEach(function () { suiteWideFoo = 0; }); describe('some nested suite', function() { var nestedSuiteBar; beforeEach(function() { nestedSuiteBar=1; }); it('nested expectation', function () { expect(suiteWideFoo).toEqual(0); expect(nestedSuiteBar).toEqual(1); }); }); it('top-level describe', function () { expect(suiteWideFoo).toEqual(0); expect(nestedSuiteBar).toEqual(undefined); // Spec will fail with ReferenceError: nestedSuiteBar is not undefined }); });
如果你想禁止Specs的运行,你可以用xit( )代替it( ). 如果你想禁止Suites的运行你可以用.xdescribe()代替describe() 。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。