单元测试使用ComponentFactory和Injector

时间:2017-08-17 21:26:04

标签: angular unit-testing angular2-directives

使用Angular 4.2,我编写了一个指令,可以动态构建一个组件,并使用Angular的ComponentFactory和Injector将其插入到DOM中。以下是代码示例:

https://plnkr.co/edit/wO9EWWJZxEL221ktsZGE?p=preview

我想为此指令编写规范。通常我会构建一个测试组件并将其连接到测试台。但是,该指令将其组件注入到文档DOM中,该文档DOM不存在于测试台中。如何测试指令的行为?

示例规范(伪代码):

@Component({
    template: '<h3 appExample>Example</h3>'
})
class TestComponent {}

describe('ExampleDirective', () => {
    let fixture: ComponentFixture<TestComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ BrowserModule ],
            declarations: [
                TestComponent,
                ExampleDirective,
                ExampleDirectiveComponent
            ]
        });

        fixture = TestBed.createComponent(TestComponent);
        fixture.detectChanges();
    });

    it('should fire directive', fakeAsync(() => {
        const template = fixture.debugElement.query(By.css('h3'));
        template.nativeElement.dispatchEvent(new Event('click'));
        fixture.detectChanges();
        tick();
        console.log('fixture', fixture.componentInstance);
    }));
});

console.log显示即使指令被触发,也没有任何东西附加到夹具上。

0 个答案:

没有答案
相关问题