繁体   English   中英

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

[英]Angular 7 Unit test case for matdialog open method

尝试在规格文件中调用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;
            });

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

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

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();
    ...
}));

暂无
暂无

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

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