Unit test views - best practice

前端 未结 1 1680
感动是毒
感动是毒 2021-01-30 09:04

Can anyone share experience with unit testing views? I read a lot of tutorials about how to do unit testing with views, but everything has some drawbacks.

I came along w

相关标签:
1条回答
  • 2021-01-30 09:41

    I think that what you're doing is a great way to unit test views. The code in your question is a good recipe for someone looking to unit test views.


    1. ng-repeat $$hashKey

    Don't worry about the data. Instead, test the result of various operations, because that's what you really care about at the end of the day. So, use jasmine-jquery to verify the state of the DOM after creation of the controller, and after simulated click()s, etc.


    2. $scope = $rootScope.$new() ain't no problem

    $rootScope is an instance of Scope, while $rootScope.$new() creates an instance of ChildScope. Testing with an instance of ChildScope is technically more correct because in production, controller scopes are instances of ChildScope as well.

    BTW, the same goes for unit testing directives that create isolated scopes. When you $compile your directive with an instance of ChildScope an isolated scope will be created automatically(which is an instance of Scope). You can access that isolated scope with element.isolateScope()

    // decalare these variable here so we have access to them inside our tests
    var element, $scope, isolateScope;
    
    beforeEach(inject(function($rootScope, $compile) {
      var html = '<div my-directive></div>';
    
      // this scope is an instance of ChildScope
      $scope = $rootScope.$new();
    
      element = angular.element(html);   
      $compile(element)($scope);
      $scope.$digest();
    
      // this scope is an instance of Scope
      isolateScope = element.isolateScope(); 
    }));
    

    3. +1 Testing Views

    Some people say test views with Protractor. Protractor is great when you want to test the entire stack: front end to back end. However, Protractor is slow, and unit testing is fast. That's why it makes sense to test your views and directives with unit tests by mocking out any part of the application that relies on the back-end.

    Directives are highly unit testable. Controllers less so. Controllers can have a lot of moving parts and this can make them more difficult to test. For this reason, I am in favor of creating directives often. The result is more modular code that's easier to test.

    0 讨论(0)
提交回复
热议问题