How to unit test an Angular 1.5 Component template?

隐身守侯 提交于 2019-12-10 18:05:42

问题


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". 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?


回答1:


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

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


来源:https://stackoverflow.com/questions/41624014/how-to-unit-test-an-angular-1-5-component-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!