本文由markdown语法编辑而成。
1. 概述:
Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.
Jasmine是一个针对JavaScript的行为驱动开发的测试框架,不依赖于任何其他的JavaScript框架或者文档对象模型(DOM)。它拥有清晰和简洁的语法,可以帮助开发者很容易地写测试。
2. Jasmine API:
以下是最简单的一个Jasmine单元测试的例子。一个测试集(test suite)中包含了一个测试点。
Describe(“A suite”, function() {
It(“contains spec with an expectation”, function(){
Expect(true).toBe(true);
});
}
(1)Describe方法:
describe方法标志着一个测试集(test suite)的开始,这个方法有两个参数,一个字符串String,一个方法function;字符串用来描述这个test suite的测试内容,function里的内容就是测试代码,也就是suite。
(2)It方法:
it方法和describe方法类似, 同样有两个参数,一个String,一个function;String用来描述测试点(spec),function是具体的测试代码。一个测试点 (spec)可以包含多个expections。
(3)Expect:
全部的断言返回true,这个测试点就通过,一个或者多个断言返回false这个测试点就不通过。
(4)Matchers:
Matchers方法返回true或者false,它决定着某一个测试点(spec)是否通过。
3. Jasmine测试常用断言
断言类型 | 断言例子 |
Expect(A).toBe(B); Expect(A).not.toBe(B); 注:toBe是和”===”相同的含义,表示两者等同. | Expect(true).toBe(true); Expect(a).toBe(true); Expect(false).not.toBe(true); |
Expect(a).toEqual(xx); Expect(A).toEqual(B); 注: toEqual是指相等,包括数字或变量的相等。 | Expect(a).toEqual(12); Expect(objectA).toEqual(objectB); |
Expect(msg).toMatch(); Expect(msg).not.toMatch(); 注:正则表达式匹配。 | var message=”foo bar baz”; Expect(message).toMatch(/bar/); Expect(message).toMatch(“bar”); Expect(message).not.toMatch(/quux/); |
Expect(a).(not.)toBeDefined(); Expect(a).(not.)toBeUndefined(); 注:表明变量是否是undefined. | var a={foo:”foo”}; Expect(a.foo).toBeDefined(); Expect(a.bar).not.toBeDefined(); |
Expect(a).toBeNull(); Expect(a).not.toBeNull(); 注: 是否是null判断. | var a=null; var foo=”foo”; Expect(a).toBeNull(); Expect(foo).not.toBeNull(); |
Expect(a).(not.)toBeTruthy(); Expect(b).(not.)toBeFalsy(); 注: 判断是否bool值相等. | var a; var foo = “foo”; expect(foo).toBeTruthy(); expect(a).not.toBeTruthy(); |
Expect(a).(not.)toBeLessThan(b); Expect(b).(not.)toBeMoreThan(b); Expect(a).toBeCloseTo(b,num); Expect(a).not.toBeCloseTo(b,num); 注:是数值比较,比较大于、小于或近似于。 | var pi=3.1415926; var e=2.78; Expect(e).toBeLessThan(pi); Expect(pi).toBeMoreThan(e); Expect(pi).not.toBeCloseTo(e,2); Expect(pi).toBeCloseTo(e,0); |
未完待续……
4. 参考资料:
- Jasmine文档
http://jasmine.github.io/2.0/introduction.html - Jasmine GitHub:
https://github.com/jasmine/jasmine - JavaScript单元测试框架-Jasmine
http://m.blog.csdn.net/blog/afandaafandaafanda/44220131# - Jasmine:基于JavaScript的行为驱动开发测试框架
http://www.lembed.com/jasmine%E5%9F%BA%E4%BA%8Ejavascript%E7%9A%84%E8%A1%8C%E4%B8%BA%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91%E6%B5%8B%E8%AF%95%E6%A1%86%E6%9E%B6/