学习后自己的理解,若有理解不正确之处,欢迎提出。
上一节说了所谓断言就是期望值与实际值比较,一致则通过,不一致则失败。
那么我们比较的类型有多少呢?
如果两个值是数值,我们可以想到:等于,不等于,大于,小于,大于等于,小于等于,约等于等
如果两个是布尔值,我们可以想到:值为ture,值为false;
如果两个是对象,我们可以想到:对象相等,被定义,未被定义,是否为null
还有一些其他的:根据字符串、正则表达式筛选是否符合规则,是否抛出异常,报错信息是否一致等等,我们还可以自定义匹配器。
数值比较
toBe(===);not.toBe;toBeGreaterThan;toBeLessThan;toBeGreaterThanOrEqual;toBeLessThanOrEqual;toBeCloseTo(四舍五入后比较,有两个参数,一个是值,一个是精度)。
布尔值比较
toBeTruthy;toBeFalsy
注意这里的falsy不是简单的false,javascript中falsy值有:0,false,空的function,空的array和空的object。
详细包括:false,null,undefined,0,NaN,”(空字符串),”“(空字符串),document.all
对象比较
toEqual,toBeDefined,toBeUndefined,toBeNull
其他
toMatch,toBeNaN,toContain,toThrow,toThrowError
在specbasic中建一个Matcher.js文件,将以下代码烤进去
describe('number compare',function(){
it('10 toBe 10',function(){
expect(10).toBe(10);
})
it('10 not toBe 9',function(){
expect(10).not.toBe(9);
})
it('10 toBeGreaterThan 7',function(){
expect(10).toBeGreaterThan(7);
})
it('10 toBeLessThan 15',function(){
expect(10).toBeLessThan(15);
})
it('10 toBeGreaterThan 9 and 10 euqal 10',function(){
expect(10).toBeGreaterThanOrEqual(9);
expect(10).toBeGreaterThanOrEqual(10);
})
it('10 toBeLessThan 15 and 10 euqal 10',function(){
expect(10).toBeLessThanOrEqual(15);
expect(10).toBeLessThanOrEqual(10);
})
describe('toBeCloseTo',function(){
it('precision is 1',function(){
expect(10.1).toBeCloseTo(10.05,1);
})
it('precision is 2',function(){
expect(10.1).not.toBeCloseTo(10.05,2);
})
})
})
describe('boolean compare',function(){
it('a is true',function(){
var a = true;
expect(a).toBeTruthy()
expect(a).not.toBeFalsy()
})
it('a is 0',function(){
var a = 0;
expect(a).toBeFalsy()
})
it('a is false',function(){
var a = false;
expect(a).toBeFalsy()
})
it('a is null object',function(){
var a;
expect(a).toBeFalsy()
})
it('a is null-string',function(){
var a = '';
var b = ""
expect(a).toBeFalsy()
expect(b).toBeFalsy()
})
it('a is NaN',function(){
var a = 0/0;
expect(a).toBeFalsy()
})
})
describe('object compare',function(){
it('a toEqual b',function(){
var a ;
var b = a;
expect(a).toEqual(b)
})
it('a id Defined and b is not defined',function(){
var a = 'happy' ;
var b ;
expect(a).toBeDefined()
expect(b).toBeUndefined()
})
it('a is null',function(){
var a = null;
expect(a).toBeNull()
})
})
describe('other compare',function(){
it('a toMatch wangmiaomiao',function(){
var a = 'my name is wangmiaomiao';
expect(a).toMatch('wangmiaomiao')
})
it('regular expression \miao',function(){
var a = 'my name is wangmiaomiao';
expect(a).toMatch('\miao')
})
it ('toThrow',function(){
var a = function(){
return c ;
}
expect(a).toThrow()
})
it ('toThrowError',function(){
var a = function(){
throw new TypeError("name is TypeError and message is this content")
}
expect(a).toThrowError(TypeError,'name is TypeError and message is this content')
})
})
在SpecRunner.html中修改如下:
<!-- include spec files here... -->
<!-- <script src="spec/Basic/Calc_spec.js"></script> -->
<script src="spec/Basic/matcher.js"></script>
运行结果:
上面的分类不是精确的,只是大概分了这么几类,容易理解一点。有些类之间是有耦合的,并非独立块。望理解。