问题
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