初探javascript单元测试框架-Jasmine

Jasmine 是一个用 Javascript 代码的行为驱动测试框架,它不依赖于任何其它 Javascript 框架。Jasmine 与 Mocha 大概是目前最火的两个单元测试框架了。

Jasmine API

describe

describe 是 Jasmine的全局函数,也称之为’测试套件’,用于创建一组相关的测试。它通常包含两个参数:描述当前套件的字符串和实际执行的函数。

1
2
3
4
5
6
7
describe('A suite is just a function', function() {
var a = true;

it('a spec', function() {
expect(a).toBe(true);
})
})

it

it块成为测试用例,定义一个单独的测试case,是测试的最小单位。一个 it 应当包含至少一个 expectation。

1
it(description, testFunction, timeout)

it 函数包含三个参数, 第一个参数为字符串,用于描述当前测试用例;第二个参数为实际执行的函数,第三个参数为一个异步的超时时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
describe('A suite is just a function', function() {
var a;

it('a spec', function() {
a = true;
expect(a).toBe(true);
})

it('another spec', function() {
a = false;
expect(a).toBe(false);
})
})

expectations

expectations 是由方法 expect 方法创建的断言, 返回 true 或 false 。expect 语句传递一个参数,及要测试的实际值,后面紧跟一个 Matchers,来判断测试是否正确。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
describe('A suite is just a function', function() {
var a;

it('a spec', function() {
a = true;
// 下面语句即为 expectation
expect(a).toBe(true);
})

it('another spec', function() {
a = false;
expect(a).toBe(false);
})
})

Matchers

Matchers 用来对实际测试值与期望值进行比较,实现断言操作。
任何Matcher都能通过在expect调用Matcher之前,通过调用not来实现一个否定断言。

常用的Matchers():

  • not 表示对后面断言的否定
  • toBe() 判断实际值与期望值是否相等,等价于 ===
  • toBeDefined() 判断变量或属性是否已声明且赋值(是否不等于undefined)
  • toBeUndefined() 判断变量或属性是否已声明且赋值(是否等于undefined)
  • toBeNull() 判断变量是否为null
  • toBeNaN() 判断变量是否为NaN(not a number)
  • toBeTruthy() 判断变量如果转换为布尔值,是否为true
  • toBeFalsy() 判断变量如果转换为布尔值,是否为false
  • toEqual() 判断变量是否相等
  • toBeLessThan() 判断实际值是否小于期望值
  • toBeLessThanOrEqual() 判断实际值是佛小于等于期望值
  • toContain() 判断数组或字符串是否包含期望值,不能用于对象判断
  • toMatch() 判断实际值是否与正则匹配

测试用例钩子函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
describe('test', function() {
beforeAll(function() {
// 在所有的Spect(it)执行之前执行,且只执行一次。
});
afterAll(function() {
// 在所有Spect(it)执行之后执行,且只执行一次。
});
beforeEach(function() {
// 在describe每个Spect(it)执行之前执行。
});
afterEach(function() {
// 在describe每个Spect(it)执行之后执行。
});
})

this 关键字

describe 里的每个 beforeEach, afterEach, it 的 this 都是相同的。

describe 嵌套

describe 可以嵌套, 不同 describe 函数体执行时,从外到内依次执行 beforeEach,每个 it 执行结束时,会按从内到外依次执行 afterEach。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
describe('test describe', function() {
var foo;
beforeAll(function() {
foo = 0;
console.log(foo);
});

afterAll(function() {
foo = 'all';
console.log(foo);
});

beforeEach(function() {
foo = 1;
console.log(foo);
});

afterEach(function() {
foo = 2;
console.log(foo);
})

it('test 1', function() {
expect(1).toBe(1);
})

describe('test inner', function() {
expect(true).toBeTruthy();
})
})