简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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