使用 Karma + Jasmine 构建 Web 测试环境(1)Jasmine 简介 更新
- UID
- 1066743
|
使用 Karma + Jasmine 构建 Web 测试环境(1)Jasmine 简介 更新
Jasmine 中的高级用法 - SpiesJasmine 还为我们提供了一些其他的方法,用于函数的元数据测试,Timeout 测试,异步调用测试等等。不过,这些方法属于 Jasmine 的高级用法,本文并不打算将它们一一列举。而是将重点放在了最有特点的 Spies 上,至于其他方法大家可以参看 。
Spy 用于模拟函数的调用,并且记录被调用的次数以及传递的参数,我们将这样的测试称为函数的元数据测试。例如
清单 6. Jasmine 中的 Spies1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| describe("A test suite for Spies", function() {
var schoolService = new SchoolService();
var teachers = null;
beforeEach(function() {
spyOn(schoolService, "getTeachers");
teachers = schoolService.getTeachers();
});
it("Spec test 1, tracks that the spy was called", function() {
expect(schoolService.getTeachers).toHaveBeenCalledTimes(1);
expect(schoolService.getTeachers).toHaveBeenCalled();
});
it("Spec test 2, tracks that the spy was called x times", function() {
teachers = schoolService.getTeachers();
expect(schoolService.getTeachers).toHaveBeenCalledTimes(2);
});
it("Spec test 3, tracks all the arguments of its calls", function() {
expect(schoolService.getTeachers).toHaveBeenCalledWith() ;
});
it("Spec test4, stops all execution on a function", function() {
expect(teachers).not.toBeDefined();
});
});
|
清单 7. 使用 Spies 模拟返回值1
2
3
4
5
6
7
8
9
10
11
12
13
| describe("A test suite for Spies", function() {
var schoolService = new SchoolService();
var teachers = null;
beforeEach(function() {
spyOn(schoolService, "getTeachers").and.returnValue({id: "016", name: "teacher6"});;
teachers = schoolService.getTeachers();
});
it("Spec test 5, when called returns the requested value", function() {
expect(schoolService.getTeachers).toHaveBeenCalledTimes(1);
expect(teachers).toBeDefined();
expect(teachers.id).toEqual("016");
});
});
|
Jasmine 是用 JavaScript 实现的,所以它也必须在 JavaScript 的环境中运行,最简单的环境也就是一个 Web 页面。所有的 spec 都可以在这个页面中运行,这个页面就叫做 Runner。
清单 8. 运行Jasmine1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine Spec Runner v2.8.0</title>
<link rel="shortcut icon" type="image/png"
href="lib/jasmine-2.8.0/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.8.0/jasmine.css">
<script src="lib/jasmine-2.8.0/jasmine.js"></script>
<script src="lib/jasmine-2.8.0/jasmine-html.js"></script>
<script src="lib/jasmine-2.8.0/boot.js"></script>
<!-- include source files here... -->
<script src="src/model.js"></script>
<!-- include spec files here... -->
<script src="spec/spec-test.js"></script>
</head>
<body>
</body>
</html>
|
其中 boot.js 文件,用于初始化 Jasmine 环境。 |
|
|
|
|
|