How do I write simple test to check the behaviour of MatDialog in Angular 2?

邮差的信 提交于 2019-12-13 03:21:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!