Jasmine 入门
Jasmine 的四个核心概念: 分组(Suites)、用例(Specs)、期望(Expectations)、匹配(Matchers).
开始捣鼓
例子1:
1 | function add(a){ |
describe 用于定义这组测试的标题
it 用于定义某个具体测试的标题
例子2:
1 | function getVal(a){ |
例子2:
1 | //匹配邮箱 |
一些常用的方法
1 | beforeEach |
异步
1 | describe("Asynchronous specs", function() { |
beforeEach 方法接受 done 表示等异步方法执行完,再调用测试用例 it
同样 it 方法中接受 done 可用于在异步节后执行测试用例
在 angular 中使用 jasmine
- 安装依赖
1 | npm install -g karma-cli |
注意:如果全局装有 karma 和 jasmine,最好删除
- 生成 karma.conf.js
1 | karma init |
一路按照提示即可
- 第一个测试
karma.conf.js
1 | files: [ |
js/greeting.js
1 | angular.module('demo', []) |
test/getGreeting.spec.js
1 | describe("getGreeting", function() { |
总结一下大致步骤
- Import the module that contains the service you’re testing.
- Inject the service you’re testing, and save it for later use. You may also want to set up mocks or spies at this point.
- Write the tests. Each one should ideally follow the pattern of Given/When/Then, an idea from BDD (Behavior-Driven Development):
- Given some particular state of my app
set up state, mock or spy functions if necessary- When I call some method
call the method you’re testing- Then that method behaves in a certain way
verify the method did the right thing