测试 Services / Factories

测试目的

  • 独立测试服务,找出 bug 和 error 。
  • 测试不需要 stubbing 处理 XHR 请求。

测试服务是最开心快乐的事情了。用单元测试或者 Midway 测试服务,因为你可以用各种姿势( 参数, 返回值, 异常,之类… )玩它。记住,单元测试和 Midway 测试在这个例子里面非常相似,但是如果你的服务有 XHR 请求,用到 $http 服务,然后你可以抓取这个请求,然后中断它,然后用 Mock 的模拟数据重写返回值,让单元测试更纯粹,但是 Midway 测试就不要这样干了。

单元测试

<!-- lang: js -->
//
// test/unit/services/servicesSpec.js
//
describe("Unit: Testing Controllers", function() {

  beforeEach(module('App'));

  it('should contain an $appStorage service',
    inject(function($appStorage) {

    expect($appStorage).not.to.equal(null);
  }));

  it('should contain an $appYoutubeSearcher service',
    inject(function($appYoutubeSearcher) {
    expect($appYoutubeSearcher).not.to.equal(null);
  }));

  it('should have a working $appYoutubeSearcher service',
    inject(['$appYoutubeSearcher',function($yt) {

    expect($yt.prefixKey).not.to.equal(null);
    expect($yt.resize).not.to.equal(null);
    expect($yt.prepareImage).not.to.equal(null);
    expect($yt.getWatchedVideos).not.to.equal(null);
  }]));

  it('should have a working service that resizes dimensions',
    inject(['$appYoutubeSearcher',function($yt) {

    var w = 100;
    var h = 100;
    var mw = 50;
    var mh = 50;
    var sizes = $yt.resize(w,h,mw,mh);
    expect(sizes.length).to.equal(2);
    expect(sizes[0]).to.equal(50);
    expect(sizes[1]).to.equal(50);
  }]));

  it('should store and save data properly',
    inject(['$appStorage',function($storage) {

    var key = 'key', value = 'value';
    $storage.enableCaching();
    $storage.put(key, value);
    expect($storage.isPresent(key)).to.equal(true);
    expect($storage.get(key)).to.equal(value);

    $storage.erase(key);
    expect($storage.isPresent(key)).to.equal(false);

    $storage.put(key, value);
    $storage.flush();
    expect($storage.isPresent(key)).to.equal(false);
  }]));

});

Midway 测试

<!-- lang: js -->
//
// test/midway/services/servicesSpec.js
//
describe("Midway: Testing Services", function() {

  var tester;
  beforeEach(function() {
    if(tester) {
      tester.destroy();
    }
    tester = ngMidwayTester('App');
  });

  it('should perform a JSONP operation to youtube and fetch data', 
    function(done) {

    var $yt = tester.inject('$appYoutubeSearcher');
    expect($yt).not.to.equal(null);

    //this is the first video ever uploaded on youtube
    //so I doubt it will be removed anytime soon
    //and should be a good testing item
    var youtubeID = 'jNQXAC9IVRw';

    $yt.findVideo(youtubeID, false,
      function(q, data) {
        expect(data).not.to.equal(null);
        expect(data.id).to.equal(youtubeID);
        done();
      }
    );
  });

});

你可能感兴趣的:(AngularJS,karma)