问题
I have the following component:
@Component({
selector: 'my-form',
templateUrl: './my-form.component.html',
})
export class MyFormComponent implements OnInit {
@Input('company') company: CompanyInfo;
private config: ConfigInterface | null;
constructor(private companyService: CompanyService, private something: Something, private dialog: MatDialog) {
}
ngOnInit() {
....
}
theMtehodWhichIWantToTest(company: string) {
if (someTest.indexOf(domain)) {
this.dialog.open(MyAllertComponent, {
data: {
title: 'blah',
},
});
}
}
}
My poor and failing unit test:
describe( 'MyFormComp', () => {
it('should open MatDialog if email is from popular domain', () => {
const dialog = {} as MatDialog;
const comp = new MyComponent({} as CompanyService, {} as Something, dialog);
comp.getCompanys(company);
expect(dialog.open(AlertComponent));
});
})
The error message: TypeError: dialog.open is not a function
Yes, I know why I have this error message - I am not mocking the dialog correctly and the functon open
is not available. Can someone tell me how to make open
available using jasmine (I.e. how to properly mock MatDialog?)
I am quite new to js unit testing so, just telling me what to google will not be very helpful for me.
回答1:
You can use the beforeEach method to create spy's for your component dependencies:
emailServiceSpy = jasmine.createSpyObj('EmailService', {});
somethingSpy = jasmine.createSpyObj('Something', {});
dialogSpy = jasmine.createSpyObj('MatDialog', ['open']);
Then provide these for your Testmoudle:
TestBed.configureTestingModule({
declarations: [YourComponent],
providers: [
{ provide: EmailService, useValue: emailServiceSpy },
{ provide: Something, useValue: somethingSpy },
{ provide: MatDialog, useValue: dialogSpy },
],
imports: [],
}).compileComponents();
And in your Test you can check if your spy-function get called:
expect(dialogSpy.open).toHaveBeenCalled();
来源:https://stackoverflow.com/questions/54146188/how-do-i-write-simple-test-to-check-the-behaviour-of-matdialog-in-angular-2