1

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

我的代码如下。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. 模态弹出组件

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

请建议我如何通过我的代码的那部分。

4

1 回答 1

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();
    ...
}));
于 2019-06-28T08:44:51.833 回答