0
点赞
收藏
分享

微信扫一扫

Chakram学习笔记 - chakram模块基本用法

这篇文章会通过具体例子介绍chakram模块的常用验证方法。

HTTP GET

使用chakram.get(url, params)完成一次HTTP GET请求。此方法返回的promise对象最终会被resolve成一个ChakramResponse对象。

Chakram把HTTP请求的结果封装到了一个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数组作为参数,返回一个promise,并且要在数组中所有promises被完成之后,promise状态才会变为fulfilled,表示异步操作成功。可以用于对多个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);
            }
        });
    });

可以实现两个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状态才会变为fulfilled,表示异步操作成功。这个方法通过记录在it()中所有chakram expectations的调用情况以及等待所有的expectation的完成,之后才使得返回的promise fulfilled,达到自动等待异步测试完成的效果。

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数组作为参数,返回一个promise,并且要在数组中所有promises被完成之后,promise状态才会变为fulfilled,表示异步操作成功。这个方法和chakram.all很类似,除了这个返回的promise状态变为fulfilled的条件是数组中最后一个promise的状态变为fulfilled,而不是全部数组的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添加不带参数的验证方法。
第二个参数plugin的类型是function,这个function接受一个ChakramResponse对象作为参数,这样就可以在方法体内对这个对象进行处理判断。

chakram.addMethod

使用chakram.addMethod(name, plugin)可以给Chakram添加带参数的验证方法。第二个参数plugin的类型是function,这个function接受一个或多个参数,且第一个参数必须是ChakramResponse对象,这样就可以在方法体内对这个对象进行处理判断。

下面是这两个方法使用的例子

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)
    ])
  });

})
举报

相关推荐

0 条评论