我正在为AngularJS应用编写一些基本的单元测试。我在UI上有一些绑定,我的指令内有一个范围变量,该变量在Promise完成时填充。
HTML:
<div id="parent">
<div id="child" ng-repeat="l in aud">
// Other Stuff
</div>
</div>
指令:
link: function(scope){
service.getArray().$promise.then(function(data){
scope.aud = data;
}
试验:
describe('my module', function () {
var $compile: ICompileService, $rootScope: IScope, directive: JQuery<HTMLElement>;
// Load the myApp module, which contains the directive
beforeEach(angular.mock.module('my-module'));
beforeEach(angular.mock.module(($provide) => {
$provide.service('service', () => {
return {
getArray: () => {
return Promise.resolve(
["item1", "item2"]
);
}
}
});
// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
beforeEach(inject(($httpBackend: IHttpBackendService, _$compile_: ICompileService, _$rootScope_: IRootScopeService) => {
$compile = _$compile_;
$rootScope = _$rootScope_.$new();
directive = $compile('<my-directive></my-directive>')($rootScope)
$rootScope.$apply();
}));
describe('account-utility directive', function () {
it('account utility directive details panel is shown on click', function () {
let list = directive.find("parent"); // Finds this
let listItems = list.find("child"); // Cannot find this. Throws error.
console.log(list); // innerHTML still shows ngrepeat unsubstituted by divs
expect(listItems.length).toBe(2);
});
});
});
我调试了整个过程,诺言得以解决,并将数据分配给范围变量'aud'。但是,似乎我的测试范围副本与应用程序不同。这是怎么回事?
当Angular的承诺得到解决时,您需要通知它,以便它将运行其肮脏的检查。
为此,您需要在$rootScope.apply()
子句中调用it
。
这样想,在每个子句中调用您的指令的$rootScope.apply()
函数之前的link
调用,该函数在Angulars队列中注册了Promise解决方案,但未得到处理。
beforeEach((done) => {
directive = $compile('<my-directive></my-directive>')($rootScope);
$rootScope.$digest();
setTimeout(() => {
$rootScope.$digest();
done();
});
});
完成可帮助您等待所有异步任务从堆栈中取出。
应用()
也可以使用