测试 Directives

测试目的

  • 测试 directive 是否在视图/DOM上起作用。

directive 是 AngularJS 的重要组成部分(其实就是自定义控件)。测试他们同样重要。当测试 directive 的时候,你应该希望看到当 directive 运行起来的时候,是否如你所希望的反应在 $scope 或者 DOM 上。directives 同样的,依赖设计,有可能触发 XHR 在后台,不过这样太不可爱了,因此测试 directives 的时候,最好三种方式都测,用来保证他们的正确性(毕竟是通用自定义控件,不能丢脸)。

单元测试:

<!-- lang: js -->
//
// test/unit/directives/directivesSpec.js
//
describe("Unit: Testing Directives", function() {

  var $compile, $rootScope;

  beforeEach(module('App'));

  beforeEach(inject(
    ['$compile','$rootScope', function($c, $r) {
      $compile = $c;
      $rootScope = $r;
    }]
  ));

  it("should display the welcome text properly", function() {
    var element = $compile('<div data-app-welcome>User</div>')($rootScope);
    expect(element.html()).to.match(/Welcome/i);
  })

});

Midway 测试:

<!-- lang: js -->
//
// test/midway/directives/directivesSpec.js
//
describe("Midway: Testing Directives", function() {

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

  afterEach(function() {
    tester.destroy();
    tester = null;
  });

  it("should properly create the youtube listings with the directive in mind", function(done) {
    var $youtube = tester.inject('$appYoutubeSearcher');

    var html = '';
    html += '<div data-app-youtube-listings id="app-youtube-listings">';
    html += ' <div data-ng-include="\'templates/partials/youtube_listing_tpl.html\'" data-ng-repeat="video in videos"></div>';
    html += '</div>';

    $youtube.query('latest', false, function(q, videos) {
      var scope = tester.viewScope().$new();
      scope.videos = videos;
      var element = tester.compile(html, scope);
      setTimeout(function() {
        var klass = (element.attr('class') || '').toString();
        var hasClass = /app-youtube-listings/.exec(klass);
        expect(hasClass.length).to.equal(1);

        var kids = element.children('.app-youtube-listing');
        expect(kids.length > 0).to.equal(true);
        done();
      },1000);
    });
  });

});

E2E测试:

<!-- lang: js -->
//
// test/e2e/directives/directivesSpec.js
//
describe("E2E: Testing Directives", function() {

  beforeEach(function() {
    browser().navigateTo('/');
  });

  it('should have a working welcome directive apply it\'s logic to the page', function() {
    browser().navigateTo('#!/videos');
    expect(browser().location().path()).toBe("/videos");
    expect(element('#app-welcome-text').html()).toContain('Welcome');
  });

  it('should have a working youtube listing directive that goes to the right page when clicked', function() {
    browser().navigateTo('#!/videos');
    element('.app-youtube-listing').click();
    expect(browser().location().path()).toMatch(/\/videos\/.+/);
  });

});

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