Matdialog打开方法的Angular 7单元测试用例

时间:2019-06-28 07:48:48

标签: angular unit-testing angular6 karma-jasmine angular-event-emitter

当我尝试在规范文件中调用dialogRef.componentInstance.onAdd方法时,出现静态null注入器错误。

我的代码如下。 1.查看器组件

    import { Component, OnInit } from '@angular/core';
    import { MatDialog } from '@angular/material';
    import { ModalPopupComponent } from '../shared/modal-popup/modal-popup.component';
    import { interval } from 'rxjs';
    @Component({
        selector: 'app-viewer',
        templateUrl: './viewer.component.html',
        styleUrls: ['./viewer.component.less']
    })
    export class ViewerComponent implements OnInit {
        userAwareNessText: string;
        secondsCounter = interval(300000);

        constructor(private dialog: MatDialog) { }

        ngOnInit() {
            this.subScribeTimer();
        }
        subScribeTimer(): void {
            this.secondsCounter.subscribe(() => {
                this.askUserAwareness();
            });
        }
        askUserAwareness(): void {
            const dialogRef = this.dialog.open(ModalPopupComponent, {
                width: '250px',
                data: ''
            });

            const sub = dialogRef.componentInstance.onAdd.subscribe((returnData: any) => {
                this.userAwareNessText = returnData;
            });
            dialogRef.afterClosed().subscribe(() => {
                sub.unsubscribe();
            });
        }
    }
  1. 模式PopupComponent

        import { Component, OnInit, ViewChild, EventEmitter } from '@angular/core';
    import { MatDialogRef } from '@angular/material';
    import { CountdownComponent } from 'ngx-countdown';
    
    @Component({
        selector: 'app-modal-popup',
        templateUrl: './modal-popup.component.html',
        styleUrls: ['./modal-popup.component.less']
    })
    export class ModalPopupComponent implements OnInit {
        onAdd = new EventEmitter();
        userAwareNessText: string;
    
        constructor(
            private dialogRef: MatDialogRef<ModalPopupComponent>) { }
    
        @ViewChild('countdown') counter: CountdownComponent;
    
        ngOnInit() {
            this.userAwareNessText = 'User is on the screen!!!';
        }
    
        finishPopUpTimer() {
            this.userAwareNessText = 'User left the screen!!!';
            this.resetTimer();
            this.closePopUp();
            this.toggleParentView();
        }
        resetTimer() {
            this.counter.restart();
        }
        closePopUp() {
            this.dialogRef.close();
            this.onAdd.emit(this.userAwareNessText);
        }
        toggleParentView() {
            this.onAdd.emit(this.userAwareNessText);
        }
    }
    

这是我的查看器组件的规范文件

    import { async, ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
    import { ViewerComponent } from './Viewer.component';
    import { MatDialog, MatDialogRef } from '@angular/material';
    import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
    import { of } from 'rxjs';
    import { ModalPopupComponent } from '../shared/modal-popup/modal-popup.component';
    import { CountdownComponent } from 'ngx-countdown';


    describe('ViewerComponent', () => {
        let component: ViewerComponent;
        let fixture: ComponentFixture<ViewerComponent>;
        let modalServiceSpy: jasmine.SpyObj<MatDialog>;
        let dialogRefSpyObj = jasmine.createSpyObj(
            {
                afterClosed: of({}),
                close: null,
                componentInstance: {
                    onAdd: (data: any) => of({ data })
                }
            }
        );


        beforeEach(async(() => {
            modalServiceSpy = jasmine.createSpyObj('modalService', ['open']); // , 'componentInstance', 'onAdd'
            TestBed.configureTestingModule({
                declarations: [ViewerComponent, ModalPopupComponent],
                providers: [
                    { provide: MatDialog, useValue: modalServiceSpy },
                ],
                schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
            })
                .compileComponents().then(() => {
                    fixture = TestBed.createComponent(ViewerComponent);
                    component = fixture.componentInstance;
                });
        }));

        beforeEach(() => {
            fixture = TestBed.createComponent(ViewerComponent);
            component = fixture.componentInstance;
            modalServiceSpy.open.and.returnValue(dialogRefSpyObj);
        });

        it('should create component', () => {
            expect(component).toBeTruthy();
        });

        it('should open popup and close popup', fakeAsync(() => {
            let fixture_modalPopup = TestBed.createComponent(ModalPopupComponent);
            let component_modalPopUp = fixture_modalPopup.componentInstance;
            fixture_modalPopup.detectChanges();
            spyOn(component_modalPopUp, 'onAdd');

            component.askUserAwareness();

            expect(modalServiceSpy.open).toHaveBeenCalled();
            expect(component_modalPopUp.onAdd).toHaveBeenCalled();
            expect(dialogRefSpyObj.afterClosed).toHaveBeenCalled();
        }));

    });

以下代码部分出现错误

const sub = dialogRef.componentInstance.onAdd.subscribe((returnData: any) => {
                this.userAwareNessText = returnData;
            });

请建议我如何传递代码的那一部分。

1 个答案:

答案 0 :(得分:0)

由于您在此处创建了间谍:

spyOn(component_modalPopUp, 'onAdd');

您提供的以下存根函数将被覆盖

componentInstance: {
    onAdd: (data: any) => of({ data })
}

您并没有从间谍返回Observable,因此您无法订阅它。

您可以在存根函数中提供间谍,例如:

componentInstance: {
    onAdd: jasmine.createSpy('onAdd')
}

然后根据用例返回测试用例中的值,

it('should open popup and close popup', fakeAsync(() => {
    spyOn(component_modalPopUp, 'onAdd');
    dialogRefSpyObj.componentInstance.onAdd.and.returnValue(of({}))
    component.askUserAwareness();
    ...
}));
相关问题