Chakram學(xué)習(xí)筆記 - chakram模塊基本用法

這篇文章會通過具體例子介紹chakram模塊的常用驗證方法。

HTTP GET

使用chakram.get(url, params)完成一次HTTP GET請求。此方法返回的promise對象最終會被resolve成一個ChakramResponse對象。

Chakram把HTTP請求的結(jié)果封裝到了一個ChakramResponse對象里面。這個對象常用的屬性有

  • body - The response body
  • url - The request's original URL
  • responseTime - The time taken to make the request (including redirects) at millisecond resolution
  • response - An http.IncomingMessage object
const chakram = require('../node_modules/chakram/lib/chakram.js'),
    expect = chakram.expect;

describe("Simple Request", function(){

let testURL = "https://api.douban.com/v2/movie/subject/26794215";

  it("should allow checking of HTTP headers", function () {
     return chakram.get(testURL).then(function(response){
       console.log(response.body);
       console.log(response.url);
       console.log(response.responseTime);
       console.log(response.response);
     });
      });
})

HTTP post

使用chakram.post(url, data, params)完成一次HTTP POST請求。此方法返回的promise對象最終會被resolve成一個ChakramResponse對象。

const chakram = require('../node_modules/chakram/lib/chakram.js'),
    expect = chakram.expect;

describe("Test HTTP POST", function(){
  var postRequest;

  before(function() {
   postRequest = chakram.post("http://httpbin.org/post", {
            nba : "nba",
            cba : "cba"
              });
          });

    it("should ensure matches json exactly", function () {
        return expect(postRequest).to.have.json('json',{
                  nba : "nba",
                  cba : "cba"
                       })
                     }
                   )
})

Three Promises Related Methods

chakram.all

chakram.all(promiseArray)接受promises數(shù)組作為參數(shù),返回一個promise,并且要在數(shù)組中所有promises被完成之后,promise狀態(tài)才會變?yōu)閒ulfilled,表示異步操作成功??梢杂糜趯Χ鄠€promises一起處理。

it("should return a different username on each request", function () {
        this.timeout(10000);
        var multipleResponses = [];
        for(var ct = 0; ct < 5; ct++) {
            multipleResponses.push(chakram.get("http://api.randomuser.me/0.6?gender=female"));
        }
        return chakram.all(multipleResponses).then(function(responses) {
            var returnedUsernames = responses.map(function(response) {
                return response.body.results[0].user.username;
            });
            while (returnedUsernames.length > 0) {
                var username = returnedUsernames.pop();
                expect(returnedUsernames.indexOf(username)).to.equal(-1);
            }
        });
    });

可以實現(xiàn)兩個response的值比對

it("should support an offset parameter", function () {
    var first = chakram.get("https://api.spotify.com/v1/search?q=random&type=artist&limit=1");
    var second = chakram.get("https://api.spotify.com/v1/search?q=random&type=artist&limit=1&offset=1");
    expect(first).to.have.json("artists.offset", 0);
    expect(second).to.have.json("artists.offset", 1);
    return chakram.all([first,second]).then(function(responses) {
        expect(responses[0].body.artists.items[0].id).not.to.equal(responses[1].body.artists.items[0].id);
        return chakram.wait();
    });
});
chakram.wait

chakram.wait()返回一個promise,并且要在所有chakram expectations被完成之后,promise狀態(tài)才會變?yōu)閒ulfilled,表示異步操作成功。這個方法通過記錄在it()中所有chakram expectations的調(diào)用情況以及等待所有的expectation的完成,之后才使得返回的promise fulfilled,達(dá)到自動等待異步測試完成的效果。

it("should support auto waiting for tests", function() {
    var response = chakram.get("http://httpbin.org/get");
    expect(response).to.have.status(200);
    expect(response).not.to.have.status(404);
    return chakram.wait();
});
chakram.waitFor

chakram.waitFor(promiseArray)接受promises數(shù)組作為參數(shù),返回一個promise,并且要在數(shù)組中所有promises被完成之后,promise狀態(tài)才會變?yōu)閒ulfilled,表示異步操作成功。這個方法和chakram.all很類似,除了這個返回的promise狀態(tài)變?yōu)閒ulfilled的條件是數(shù)組中最后一個promise的狀態(tài)變?yōu)閒ulfilled,而不是全部數(shù)組的promise。

it("should support grouping multiple tests", function () {
    var response = chakram.get("http://httpbin.org/get");
    return chakram.waitFor([
        expect(response).to.have.status(200),
        expect(response).not.to.have.status(404)
    ]);
});

兩種自定義assertion方法

chakram.addProperty

使用chakram.addProperty(name, plugin)可以給Chakram添加不帶參數(shù)的驗證方法。
第二個參數(shù)plugin的類型是function,這個function接受一個ChakramResponse對象作為參數(shù),這樣就可以在方法體內(nèi)對這個對象進(jìn)行處理判斷。

chakram.addMethod

使用chakram.addMethod(name, plugin)可以給Chakram添加帶參數(shù)的驗證方法。第二個參數(shù)plugin的類型是function,這個function接受一個或多個參數(shù),且第一個參數(shù)必須是ChakramResponse對象,這樣就可以在方法體內(nèi)對這個對象進(jìn)行處理判斷。

下面是這兩個方法使用的例子

const chakram = require('../node_modules/chakram/lib/chakram.js'),
    expect = chakram.expect;

describe("Check Wolf Warrir 2", function(){

  before(function(){

    chakram.addProperty("WJisDirector", function (respObj) {
        let hostMatches = /1000525/.test(respObj.body.directors[0].id);
        this.assert(hostMatches,
            'expected director of this movie is: '+respObj.body.directors[0].id,
            'expected director of this movie is: '+respObj.body.directors[0].id
          );
    });

    chakram.addMethod("haveHighAverageRating", function (respObj, average) {
      let ratingRangeResult = respObj.body.rating.average >= average;
      this.assert(ratingRangeResult,
          'expected average rating of this movie is: '+ respObj.body.rating.average
        );
     });

     chakram.addMethod("BeOnYearAt", function (respObj, year) {
          expect(respObj).to.have.json("year", year);
      });

  });

  it("should be a movie directed by WuJing", function () {
    let response = chakram.get("https://api.douban.com/v2/movie/subject/26363254");
    return chakram.waitFor([
      expect(response).to.be.WJisDirector,
      expect(response).to.be.BeOnYearAt("2017"),
      expect(response).to.have.haveHighAverageRating(7)
    ])
  });

})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Promiese 簡單說就是一個容器,里面保存著某個未來才會結(jié)束的事件(通常是一個異步操作)的結(jié)果,語法上說,Pr...
    雨飛飛雨閱讀 3,491評論 0 19
  • 00、前言Promise 是異步編程的一種解決方案,比傳統(tǒng)的解決方案——回調(diào)函數(shù)和事件——更合理和更強大。它由社區(qū)...
    夜幕小草閱讀 2,227評論 0 12
  • 你不知道JS:異步 第三章:Promises 接上篇3-1 錯誤處理(Error Handling) 在異步編程中...
    purple_force閱讀 1,498評論 0 2
  • Promise的含義: ??Promise是異步編程的一種解決方案,比傳統(tǒng)的解決方案——回調(diào)函數(shù)和事件——更合理和...
    呼呼哥閱讀 2,275評論 0 16
  • 已經(jīng)過去好多天,有一件在別人看來微不足道的小事,卻一直蕩漾在我心底,時時刻刻溫暖著我,也感動著我,讓我對有些人或有...
    枯藤殘鴉閱讀 474評論 0 1

友情鏈接更多精彩內(nèi)容