开通了博客,恰巧这两天在看Jasmine的东西,看了一点点别人写的文章,如今为止对jasmine的认识就是:正则表达式
一个js单元测试的框架数组
赫赫 冷笑。。。(废话)框架
看到如今看到了如下几个重要的知识点:ide
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里面被叫作断言,通俗点意思就是语言的意思吧。ui
在specs中利用expectations来断言你的代码是否是成立。expectations用expect()方法来定义。在一个spec里面,只有全部的expectations都为true时,这个spec才经过,不然失败this
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是个菜鸟,还须要无尽的学习和钻研