Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  105] [ 3]  / answers: 1 / hits: 67045  / 6 Years ago, thu, october 25, 2018, 12:00:00

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.service.ts



@Injectable()
export class ModalService {

constructor(private dialog: MatDialog) { }

public open<modalType>(modalComponent: ComponentType<modalType>): Observable<any> {
let dialogRef: MatDialogRef<any>;

dialogRef = this.dialog.open(modalComponent, {
maxWidth: '100vw'
});
console.log(dialogRef)
dialogRef.componentInstance.body = body;

return dialogRef.afterClosed().pipe(map(result => console.log('test'); );
}

}


modal.service.spec.ts



export class TestComponent  {}


describe('ModalService', () => {
let modalService: ModalService;

const mockDialogRef = {
open: jasmine.createSpy('open')
};

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ MatDialogModule ],
providers: [
ModalService,
MatDialogRef,
{ provide: MatDialog, useClass: MatDialogStub }
]
}).compileComponents();

modalService = TestBed.get(ModalService);
}));


it('open modal', () => {
modalService.open(DummyComponent, '300px');
expect(modalService.open).toHaveBeenCalled();

});

});


So with that code the error is



TypeError: Cannot read property 'componentInstance' of undefined


Can you help me how to make this successful? Help is much appreciated.


More From » angular

 Answers
11

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

[#53248] Tuesday, October 23, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zayne

Total Points: 366
Total Questions: 98
Total Answers: 98

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;