【问题标题】:How do I write simple test to check the behaviour of MatDialog in Angular 2?如何编写简单的测试来检查 Angular 2 中 MatDialog 的行为?
【发布时间】:2019-01-11 12:02:30
【问题描述】:

我有以下组件:

@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',
        },
      });
    }
  }
}

我糟糕且失败的单元测试:

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

错误信息:TypeError: dialog.open is not a function

是的,我知道为什么会出现此错误消息 - 我没有正确模拟对话框,并且函数 open 不可用。有人可以告诉我如何使用jasmine 使open 可用(即如何正确模拟 MatDialog?)

我对 js 单元测试很陌生,所以只告诉我用谷歌搜索什么对我没有太大帮助。

【问题讨论】:

    标签: javascript angular typescript unit-testing jasmine


    【解决方案1】:

    您可以使用 beforeEach 方法为您的组件依赖项创建 spy:

    emailServiceSpy = jasmine.createSpyObj('EmailService', {});
    somethingSpy = jasmine.createSpyObj('Something', {});
    dialogSpy = jasmine.createSpyObj('MatDialog', ['open']);
    

    然后为您的 Testmoudle 提供这些:

    TestBed.configureTestingModule({
      declarations: [YourComponent],
      providers: [
        { provide: EmailService, useValue: emailServiceSpy },
        { provide: Something, useValue: somethingSpy },
        { provide: MatDialog, useValue: dialogSpy },
      ],
      imports: [],
    }).compileComponents();
    

    在您的测试中,您可以检查您的间谍功能是否被调用:

    expect(dialogSpy.open).toHaveBeenCalled();
    

    【讨论】:

    • 谢谢。我这样做了,但现在我有:createSpyObj requires a non-empty array or object of method names to create spies for thrown TypeError: Cannot read property 'open' of undefined
    • 我的错误,我更新了我的例子;这里是茉莉花的例子 - createSpy jasmine.github.io/2.0/introduction.html
    • 还是一样:createSpyObj requires a non-empty array or object of method names to create spies for thrown TypeError: Cannot read property 'open' of undefined 我还添加了以下行:spyOn(dialogSpy, 'open'); 但没有帮助
    • mh... 也许这样:openSpy = jasmine.createSpy('open'); dialogSpy = jasmine.createSpyObj('dialog', { open: openSpy });
    猜你喜欢
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2020-05-20
    • 2015-10-03
    • 2015-08-28
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多