【发布时间】:2018-01-30 16:59:33
【问题描述】:
我正在通过链接函数对 Angular 指令进行单元测试。通过将指令编译为 建议在这里 - http://brilliantbritz.com/2015/02/04/getting-the-isolate-scope-of-a-directive/
第一组测试运行良好,并且 我可以访问 element.scope() 对象,即指令的 isolatedScope。
但是在运行以下测试以从链接函数中获取 scope.welcomeMessage 值时。
它返回未定义:
it("should contain a welcomeMessage scope value", function() {
console.log(element.scope()); //value present in scope object
expect(element.scope().welcomeMessage).toBe("Hello World!"); //undefined
});
我通过记录包含welcomeMessage 的 element.scope() 值来调试此问题。
问题:
如何访问 Jasmine 测试规范中的链接函数范围值?
my-app.spec.js
describe("my-app", function() {
var $scope, $compile, element;
beforeEach(function(){
//register module and mock dependency
angular.mock.module("my-app");
});
beforeEach(inject(function($rootScope, _$compile_) {
$scope = $rootScope.$new(), //create instance of rootScope
$compile = _$compile_; // compile attaches directives to HTML template
element = $compile("<my-app></my-app>")($scope);
$scope.$digest(); //loop through DOM watchers, check values and trigger listeners
}));
it("should contain a defined scope", function() {
expect(element.scope()).toBeDefined(); //true
});
it("should contain a welcomeMessage scope value", function() {
console.log(element.scope());
expect(element.scope().welcomeMessage).toBe("Hello World!"); //undefined
});
});
element.scope()的日志值
LOG LOG: Scope{$$childTail: Scope{$id: 12, $$childTail: null, $$childHead: null, $$prevSibling: null, $$nextSibling: null, $$watchers:
[..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ...], $parent: Scope{$$childTail: ..., $$childHead: ...,
$$nextSibling: ..., $$watchers: ..., $$listeners: ..., $$listenerCount: ..., $$watchersCount: ..., $id: ..., $$ChildScope: ..., $parent: ..., $$prevSibling: ...},
$$phase: null, $root: Scope{$id: ..., $$childTail: ..., $$childHead: ..., $$prevSibling: ..., $$nextSibling: ..., $$watchers: ..., $parent: ..., $$phase: ...,
$root: ..., $$destroyed: ..., $$listeners: ..., $$listenerCount: ..., $$watchersCount: ..., $$isolateBindings: ..., $$asyncQueue: ..., $$postDigestQueue: ...,
$$applyAsyncQueue: ..., $$ChildScope: ...}, $$destroyed: false, $$listeners: Object{$destroy: ...}, $$listenerCount: Object{$destroy: ...}, $$watchersCount: 21,
$$isolateBindings: Object{}, welcomeMessage: 'Hello World!'}, $$childHead: Scope{$id: 12, $$childTail: null, $$childHead: null, $$prevSibling: null, $$nextSibling: null,
指令要点
(function() {
var component = {
id: "my-app",
name: "my-app",
templateUrl: "my-app/my-app.html"
};
component.ui = angular.module("my-app");
component.ui.directive("myApp", fizzComponent);
function fizzComponent() {
function fizzContainer(scope, element, params) {
scope.welcomeMessage = "Hello World!";
}
return {
scope: {},
replace: true,
link: fizzContainer,
templateUrl: component.templateUrl
};
}
})();
【问题讨论】:
标签: angularjs unit-testing jasmine