打开md-dialog的测试组件 [英] Testing component that opens md-dialog

查看:99
本文介绍了打开md-dialog的测试组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为打开对话框的Angular组件编写单元测试,但由于无法触发对话框的关闭而无法这样做.

I am trying to write a unit test for an Angular component that opens a dialog, but am unable to do so because I cannot trigger the closing of the dialog.

如何使md对话框从测试用例中解决?

How can I cause the md dialog to resolve from the test case?

我创建了一个带有基本示例的存储库,可以在该示例中重现该问题,并复制了下面的主要内容.有一个index.html可以手动验证代码是否正常工作,一个显示问题的测试用例,以及一个如何在md代码中编写测试的示例.

I have created a repository with a basic example where the problem can be reproduced, and copied the central bits below. There is an index.html to manually verify that the code is working, a test case that displays the problem and an example of how the tests are written in the md code.

存储库- https://github.com/gseabrook/md-dialog-test-问题

该组件非常基础

angular
.module('test', ['ngMaterial'])
.component('dialogTest', {
    template: '<button ng-click="showDialog()">Show Dialog</button>',
    controller: function($scope, $mdDialog) {
        var self = this;

        $scope.showDialog = function() {
            self.dialogOpen = true;

            var confirm = $mdDialog.confirm()
                .title('Dialog title')
                .ok('OK')
                .cancel('Cancel');

            $mdDialog.show(confirm).then(function(result) {
                self.dialogOpen = false;
            }, function() {
                self.dialogOpen = false;
            });
        }
    }
});

测试也很简单

it("should open then close the dialog", function() {
    var controller = element.controller("dialogTest");

    expect(controller.dialogOpen).toEqual(undefined);

    expect(element.find('button').length).toEqual(1);
    element.find('button').triggerHandler('click');

    expect(controller.dialogOpen).toBeTruthy();

    rootScope.$apply();
    material.flushInterimElement();

    element.find('button').eq(2).triggerHandler('click');

    rootScope.$apply();
    material.flushInterimElement();

    expect(controller.dialogOpen).toBeFalsy();
});

推荐答案

我设法通过设置根元素来解决此问题,因为该问题似乎与测试中正在编译的元素与与有角度的根元素断开连接有关-material也附加了对话框.

I managed to resolve the issue by setting the root element as the problem seemed to be related to element being compiled in the test being unconnected with the root element that angular-material appended the dialog too.

我已经用完整的代码更新了github存储库,但重要的是

I've updated the github repository with the full code, but the important bits are

beforeEach(module(function($provide) {
    rootElem = angular.element("<div></div>")
    $provide.value('$rootElement', rootElem);
}));

beforeEach(inject(function(_$rootScope_, _$compile_, $mdDialog, _$material_) {
    ...
    element = getCompiledElement();
    angular.element(window.document.body).append(rootElem);
    angular.element(rootElem).append(element);
}));

这篇关于打开md-dialog的测试组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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