前言
如果要挖井,就要挖到水出為止。
明晚公開課給大家講講如何用chai.js斷言,有用過postman只會右側點來自動生成斷言代碼,或在公司應用postman的朋友們都來聽聽。
一、chai.js斷言介紹
- 是一套TDD(測試驅動開發)/BDD(行為驅動開發)的斷言庫
- 包含有3個斷言庫支持BDD風格的expect/should和TDD風格的assert
- 可以高效的和任何js測試框架搭配使用(支持在postman中應用)
二、postman設置斷言的流程
- 在tests頁簽截取要對比的實際響應信息(響應頭、響應正文、響應狀態碼等)
- 利用斷言語句 tests[] 或 chai.js 形式把實際響應信息與期望結果對比
- 執行請求進行結果查看
三、截取實際響應信息的新老版本代碼對比
截取名稱 |
老版本 |
新版本 |
響應狀態碼 |
responseCode.code |
pm.response.code |
響應狀態信息 |
responseCode.name |
pm.response.status |
響應頭 |
postman.getResponseHeader('c_k') |
pm.response.headers.get('c_k') |
響應cookie |
postman.getResponseCookie('c_n').value |
pm.cookies.get('c_n') |
響應正文 |
responseBody |
pm.response.text() |
json格式響應正文 |
JSON.parse(responseBody) |
pm.response.json() |
響應時間 |
responseTime |
pm.response.responseTime |
四、tests斷言基本語法
tests["case01 驗證是否為true"] = true; //false
tests["case02 驗證是否1+1=2"] = 1+1 === 2; //判斷是否相等
tests["case03 驗證是否包含123"] = "1234567hello".has("123"); //判斷是否包含
tests["case04 驗證是否3>5"] = 3 > 5 ; //判斷是否相等
tests["case05 與運算"] = 3 > 2 && 3>1 ; //與運算
tests["case06 或運算"] = 3 > 2 || 3>5 ; //或運算
tests["case07 非運算"] = !(3 > 2); //非運算
五、chai.js斷言語法
pm.test("測試用例標題", function () {
pm.expect(true).to.be.true; //chai.js斷言編寫處
});
pm.expect(2<5 && 3<6).to.be.true; //判斷是否為true
pm.expect('everything').to.be.ok; //判斷是否為真值 非空、非0 即為真
pm.expect('hello').to.equal('hello'); //判斷是否相等
pm.expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); //判斷是否深度相等
pm.expect('foobar').to.have.string('bar'); //判斷是否包含字符串
pm.expect('foobar').to.match(/^foo/); //判斷是否包含,支持正則表達式
......
pm.test("Status code is 200", function () {
pm.response.to.have.status(200); //判斷響應狀態碼是否是200
});
pm.test("Content-Type is present", function () {
pm.response.to.have.header("Content-Type"); //判斷響應頭部信息是否包含Content-Type字段
});
- 5.3 tv4(Tiny Validator for JSON data)
postman使用tv4和chai.js斷言庫可以進行json schema(結構)的斷言
var schema ={
"type":"object", //表示當前節點的類型,最外層type代表json的最外層是什么樣的類型
"properties":{ //代表當前節點的子節點信息。如 access_token 和 expires_in
"access_token":{
"type":"string"
},
"expires_in":{
"type": "integer"
}
},
"required": [ //一個數組類型,代表當前節點下必需的節點key
"access_token",
"expires_in"
]
}
pm.test('Json Schema is valid', function() {
var jsonData = pm.response.json();
pm.expect(tv4.validate(jsonData, schema)).to.be.true;
});
六、總結及反思
- 實際工作中,斷言庫功能強大好用即可
- json schema可以好好研究利用在接口測試過程中