【问题标题】:Unit Test Angular Component Using TemplateRefs使用 TemplateRefs 对 Angular 组件进行单元测试
【发布时间】:2019-05-16 23:10:46
【问题描述】:

我正在尝试使用 TemplateRef 为 Angular 组件编写单元测试。这是整个组件、TypeScript 和 HTML:

<!-- alerts-display.component.html -->
<ng-template 
    ngFor 
    let-alert 
    [ngForOf]="alerts$ | async" 
    [ngForTemplate]="alertTemplate">
</ng-template>

和

export class AlertsDisplayComponent implements OnInit {
    public alerts$: Subject<Alert[]>;
    @ContentChild(TemplateRef)
    alertTemplate: TemplateRef<NgForOfContext<Alert>>;
    constructor(private _alertToaster: AlertToasterService) {}

    ngOnInit() {
        this.alerts$ = this._alertToaster.alerts$;
    }
}

基本上,我使用异步管道从服务订阅主题,该服务将为我提供要显示的警报列表,最终开发人员可以传入警报模板(即可以传递引导警报组件,或他们自己的实现)。

我想编写一个单元测试,以确保在向主题添加警报时,将一个元素输出到页面。到目前为止,这是我的单元测试代码:

@Component({
    selector: 'app-test-host',
    template: `
        <hsa-alerts-display>
            <ng-template let-alert>
                <p>{{ alert.message }}</p>
            </ng-template>
        </hsa-alerts-display>
    `,
})
class TestHostComponent {
    @ViewChild(AlertsDisplayComponent) alertsDisplayComponent: AlertsDisplayComponent;
}

describe('AlertsDisplayComponent', () => {
    let component: TestHostComponent;
    let fixture: ComponentFixture<TestHostComponent>;
    let mockAlertsToasterService: AlertToasterService;

    beforeEach(async(() => {
        mockAlertsToasterService = jasmine.createSpyObj(['toString']);
        mockAlertsToasterService.alerts$ = new Subject<Alert[]>();
        TestBed.configureTestingModule({
            declarations: [AlertsDisplayComponent, TestHostComponent],
            providers: [{ provide: AlertToasterService, useValue: mockAlertsToasterService }],
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TestHostComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should show an element for each item in the array list', fakeAsync(() => {
        mockAlertsToasterService.alerts$.next([{ message: 'test message', level: 'success' }]);

        tick();

        const ps = fixture.debugElement.queryAll(By.css('p'));

        expect(ps.length).toBe(1);
    }));
});

我为测试创建了一个测试主机组件,并试图模拟该服务以添加一条消息。然后我尝试通过fixture 找到p 元素,但该测试失败;它改为 0。我已经尝试了几个不同的变体,但不知道我是否走在正确的轨道上。

任何帮助将不胜感激!

Here's a Stackblitz example as well.

【问题讨论】:

    标签: angular unit-testing


    【解决方案1】:

    我上面的问题中的所有内容都是正确的,我唯一错过的是在上次测试中的tick() 之后添加一个fixture.detectChanges()。

    完成后,更新模板,输出TestHostComponent提供的p标签,可以找到并统计。

    【讨论】:

      猜你喜欢
      • 2019-01-02
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 2020-02-13
      相关资源
      最近更新 更多