首页 > 解决方案 > Angular Jasmine 测试:无法测试材料表按钮的单击事件

问题描述

我正在角度测试文件中编写代码来测试材料对话框按钮的单击。当我运行我的测试时,我收到错误无法读取 null 的属性 'triggerEventHandler'

 const setupComponent = () => {
    fixture = TestBed.createComponent(CountryComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  };

  beforeEach(() => {

    mockXYZApiServiceApiService = new Mock<XYZApiService>({
      getCountries: () => of(countryGridDataModel)
    });

    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, MatDialogModule ],
      declarations: [CountryComponent],
      providers: [
        {
          provide: XYZApiServiceApiService,
          useFactory: () => mockXYZApiServiceApiService.Object,
        }

      ],
    })
    .compileComponents();
  });

     fit('should call the mat dialog open On View click', fakeAsync(async () => {
        setupComponent();
        fixture.debugElement
          .query(By.css('#btnViewCountry'))
          .triggerEventHandler('click', {});
        await fixture.whenStable();
        expect(component.dialog.open).toHaveBeenCalled();
      }));

标签: angularkarma-jasmine

解决方案


要调试,请确保它#btnViewCountry存在且未被*ngIf.

 fit('should call the mat dialog open On View click', fakeAsync(async () => {
        setupComponent();
        // add this log to output the whole HTML and ensure that
        // #btnViewCountry is present
        console.log(fixture.nativeElement);
        fixture.debugElement
          .query(By.css('#btnViewCountry'))
          .triggerEventHandler('click', {});
        await fixture.whenStable();
        expect(component.dialog.open).toHaveBeenCalled();
      }));

推荐阅读