AngularJS:测试指令,诺言完成后未重新呈现HTML [英] AngularJS : Testing directive, HTML not re-rendered after promise completion

查看:72
本文介绍了AngularJS:测试指令,诺言完成后未重新呈现HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为AngularJS应用程序编写一些基本的单元测试.我在UI上有一些绑定,指令中包含一个范围变量,该变量在promise的完成时填充.

I am writing some basic unit tests for my AngularJS app. I have some bindings on the UI with a scope variable inside my directive whichis populated on the completion of a 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);
            });
        });

});

我调试了整个过程,并解决了promise,并将数据分配给范围变量"aud".但是,似乎我的测试范围副本与应用程序不同.这是怎么回事?

I debugged the whole thing and the promise is resolved and the data is assigned to the scope variable 'aud'. However seems like my copy of scope for the test and the app are different. Whats going on here?

推荐答案

beforeEach((done) => {
        directive = $compile('<my-directive></my-directive>')($rootScope);
        $rootScope.$digest();

        setTimeout(() => {
            $rootScope.$digest();
            done();
        });
    });

完成可以帮助您等待直到所有异步任务都从堆栈中取出.

Done helps you wait till all asynchronous tasks are picked up from the stack.

apply()

apply()

也可以

这篇关于AngularJS:测试指令,诺言完成后未重新呈现HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆