如何对Angular 1.5 Component模板进行单元测试? [英] How to unit test an Angular 1.5 Component template?

查看:71
本文介绍了如何对Angular 1.5 Component模板进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是我的测试:

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

    };

}

我得到的是Original Foo ,而不是改变了Foo。因此,即使我在测试中更改 scope.foo 变量,它也会使用组件(或控制器)上的变量。

And what I get is "Original Foo", not "Changed Foo". So, even if I change the scope.foo variable in my test, it uses the one on the component (or on the controller).

所以关于如何更改测试中的组件变量的任何想法,所以当我编译模板时它会捕获这些更改。

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 不影响组件绑定。 foo 范围属性不是 foo 属性。

scope.foo doesn't affect component bindings. foo scope property is not foo attribute.

这可能应该像

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

scope.$digest();

var componentScope = component.isolateScope();

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

这篇关于如何对Angular 1.5 Component模板进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆