繁体   English   中英

测试ES5中的Angular 2组件?

[英]Test Angular 2 component in ES5?

我正在启动一个新的Angular 2应用程序。 我有一个简单的组件,它实际上是一个下拉选择框。 组件将一些对象作为属性(在应用程序中,通过包含模板中组件DOM元素上的属性)。

Angular 2的官方文档尚无测试组件的示例。 我将如何测试组件的实际视图-检查是否根据在组件上设置的数据创建了适当的DOM元素?

我可以通过执行ng.core.Injector.resolveAndCreate([...dependencies...]).get(MyClassName)来创建组件之一。 但这实际上并不能构造视图,也不能让我传入要设置为刚创建的组件属性的数据。

遵循您在文档和回购源代码中看到的内容并不困难。 这是我所做的设置,它可以正常工作。

首先从文档中,我选择了茉莉花示例设置

<link rel="stylesheet" href="node_modules/jasmine-core/lib/jasmine-core/jasmine.css">
<script src="node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
<script src="node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
<script src="node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>

然后是angular2的设置。 您可能已经知道,当您在ES5中编写代码时,必须使用UMD捆绑软件

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/rxjs/bundles/Rx.umd.min.js"></script>
<script src="node_modules/angular2/bundles/angular2-all-testing.umd.dev.js"></script>

现在重要的部分是测试。 这里的主要任务是创建一个测试组件

var TestComponent = ng.core.
    Component({
        selector: 'cmp',
        template : '' // Left it blank, we override it when testing
    }).Class({
        constructor: function() {
            this.someProperty = 'Initial value';
        }
    });

创建组件后,可以使用TestComponentBuilder对其进行测试

ng.testing.describe('Component building', function() {

    ng.testing.it('should detect when a property changes', 
        ng.testing.inject([ng.testing.TestComponentBuilder], function(tcb) {
            tcb
                .overrideTemplate(TestComponent, '<div>{{someProperty}}</div>')
                .createAsync(TestComponent)
                .then(function(fixture) {

                    // Triggers change detection so 
                    // the div actually contains the property value
                    fixture.detectChanges();

                    // Check if the div contains the correct value
                    expect(fixture.nativeElement.innerText).toEqual('Initial value');

                    // Change property's value
                    fixture.componentInstance.someProperty = 'New value';

                    // Triggers change detection again
                    fixture.detectChanges();

                    // Check, again, if the div contains the new value
                    expect(fixture.nativeElement.innerText).toEqual('New value');
                });
        }));
});

请注意,我使用的是ng.testing.(describe/it/etc)因为来自jasmine的这些功能已修补为可与angular2一起使用。

从这一点开始,将非常容易继续。 您已经拥有整个仓库,可以查看其规格 NgFor是一个有趣的例子 您可以遵循TS / ES6示例,它们是相同的。

这是带有复制功能的plnkr

参考

您也可以在AngularConnect 2015上查看Julie Ralph的回购(ng2-test-seed)和她的演讲

希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM