MatDialog Service Unit Test Angular 6 Error

后端 未结 3 1099
长情又很酷
长情又很酷 2020-12-14 16:37

I\'m having modal service to open, confirm and close dialog and i am making its unit test file but i got and error on Angular and this is the code.

modal.ser

3条回答
  •  感动是毒
    2020-12-14 16:57

    Testing mat-dialogs can be tricky. I tend to use a spy object for the return from a dialog open (dialogRefSpyObj below) so I can more easily track and control tests. In your case it might look something like the following:

    describe('ModalService', () => {
        let modalService: ModalService;
        let dialogSpy: jasmine.Spy;
        let dialogRefSpyObj = jasmine.createSpyObj({ afterClosed : of({}), close: null });
        dialogRefSpyObj.componentInstance = { body: '' }; // attach componentInstance to the spy object...
    
        beforeEach(() => {
            TestBed.configureTestingModule({
                imports: [MatDialogModule],
                providers: [ModalService]
            });
            modalService = TestBed.get(ModalService);
        });
    
        beforeEach(() => {
            dialogSpy = spyOn(TestBed.get(MatDialog), 'open').and.returnValue(dialogRefSpyObj);
        });
    
        it('open modal ', () => {
            modalService.open(TestComponent, '300px');
            expect(dialogSpy).toHaveBeenCalled();
    
            // You can also do things with this like:
            expect(dialogSpy).toHaveBeenCalledWith(TestComponent, { maxWidth: '100vw' });
    
            // and ...
            expect(dialogRefSpyObj.afterClosed).toHaveBeenCalled();
        });
    });
    

提交回复
热议问题