Jasmine学习笔记(1)
开通了博客,恰巧这两天在看Jasmine的东西,看了一点点别人写的文章,现在为止对jasmine的认识就是:
一个js单元测试的框架
赫赫 冷笑。。。(废话)
看到现在看到了以下几个重要的知识点:
Specs,Expectations,Suites,Matchers
Specs:
specs就是你测试的主体,是js的函数。用jasmine的全局方法it()定义,有两个参数一个是string,一个是function string是用来描述这个specs的,要让你自己包括看到的人能明白这个specs是做什么的 function里面就是你测试的东西了
it('Student must defined', function () {
var foo = 0;
foo++;
});
Expectations:
在jasmine里面被叫做断言,通俗点意思就是语言的意思吧。
在specs中利用expectations来断言你的代码是不是成立。expectations用expect()方法来定义。在一个spec里面,只有所有的expectations都为true时,这个spec才通过,否则失败
it ('should increment a variable',function(){
var foo = 0;
foo++;
expect(foo).toEqual(1);
})
Suites:
suites相当于是specs的集合,很多specs被组织在suites中。suites使用全局方法describe()定义,string和function
describe('Calculator', function () { it('can add a number', function () { ... }); it('can multiply some numbers', function () { ... }); });
同一个suite中的specs共用一个函数作用域,也就是说在一个suites中声明的变量可以被这个suites中所有的specs访问
1 describe('Calculator', function () { 2 3 var counter = 0 4 5 it('can add a number', function () { 6 7 counter = counter + 2; // counter was 0 before 8 9 expect(counter).toEqual(2); 10 }); 11 12 it('can multiply a number', function () { 13 14 counter = counter * 5; // counter was 2 15 16 before expect(counter).toEqual(10); 17 18 }); 19 20 });
如果想让一个变量在每个spec里面重置为某一个值,可以使用beforeEach()
beforeEach(function(){ a=0; })
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() 。
Matchers
expect(x).toEqual(y); //当x和y相等时候通过,toEqual也可以判断对象 expect(x).toBe(y); //当x和y是同一个对象时候通过 expect(x).toMatch(pattern); //x匹配pattern(字符串或正则表达式)时通过 expect(x).toBeDefined(); // x不是undefined时通过 expect(x).toBeUndefined(); // x 是 undefined时通过 expect(x).toBeNull(); //x是null时通过 expect(x).toBeTruthy(); //x和true等价时候通过 expect(x).toBeFalsy(); //x和false等价时候通过 expect(x).toContain(y); //x(数组或字符串)包含y时通过 expect(x).toBeLessThan(y); //x小于y时通过 expect(x).toBeGreaterThan(y); // x大于y时通过
expect(x).toMatch(/y/i) ; //匹配正则表达式
expect(function(){fn();}).toThrow(e); //函数fn抛出异常时候通过
所有的matchers匹配器支持添加 .not反转结果:
expect(x).not.toEqual(y);
还有一种自定义Matchers的情况:
matcher使用this.actual接受到一个实际值(该匹配函数也可以包括0或多个参数)当实际值通过匹配,返回一个ture或false
toBeLessThan: function(expected) { return this.actual < expected; };
Setup方法:
beforeAll:在每个suite里面所有的spec执行之前运行
beforeEach:在suite里面每一个spec执行之前执行
Teardown方法:
afterAll:在每个suite里面所有的spec执行之后运行
afterEach:在suite里面每一个spec执行之后执行
暂时就这么多了,lz是个菜鸟,还需要无尽的学习和钻研