简体   繁体   English

如何对Angular 1.5 Component模板进行单元测试?

[英]How to unit test an Angular 1.5 Component template?

So, here's my test: 所以,这是我的测试:

describe('My Test', function(){

  var $componentController, $compile, controller, scope;

  beforeEach(inject(function($injector, $rootScope, $templateCache){

    $templateCache.put('my-component.html', '<h1>{{ $ctrl.foo }}</h1>');

    $componentController = $injector.get('$componentController');

    var bindings = {
      foo: 'A Foo'
      };

    scope = $rootScope.$new();

    controller = $componentController('myComponent', { $scope: {} }, bindings);

    }));

  it('should render the correct html', function(){

    scope.foo = 'Changed Foo';

    var element = angular.element(
      '<my-component foo="Original Foo"></my-component>'
      );

    var template = $compile(element)(scope);

    scope.$digest();

    var templateAsHtml = template.html();

    console.log(templateAsHtml);

    };

}

And what I get is "Original Foo" , not "Changed Foo" . 我得到的是“Original Foo” ,而不是“改变了Foo” So, even if I change the scope.foo variable in my test, it uses the one on the component (or on the controller). 因此,即使我在测试中更改了scope.foo变量,它scope.foo使用组件(或控制器)上的变量。

So any idea on how to change the component variables on the test, so when I compile the template it catches those changes. 所以关于如何在测试中更改组件变量的任何想法,所以当我编译模板时它捕获这些更改。

Basically what I want is to be able to access and modify the controller variables, so then I can test certain output depending on the controller variables values. 基本上我想要的是能够访问和修改控制器变量,因此我可以根据控制器变量值测试某些输出。 Does this make sense? 这有意义吗?

scope.foo doesn't affect component bindings. scope.foo不会影响组件绑定。 foo scope property is not foo attribute. foo scope属性不是foo属性。

This likely should be tested like 这可能应该像测试一样

var component = $compile('<my-component foo="{{ foo }}">')(scope);

scope.$digest();

var componentScope = component.isolateScope();

expect(component.html())...
expect(componentScope.$ctrl.foo)...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM