Angular 5 / Jasmine单元测试-无法读取未定义的属性'componentInstance'

时间:2018-07-16 07:46:45

标签: angular jasmine karma-jasmine

我的单元测试中有一个奇怪的错误,由于某种原因,我无法确定为什么会出现此错误。您只有两个测试。一个用于确保创建组件,另一个用于检查在调用组件方法时是否调用Mat Dialog .open方法...没什么太复杂的。这是我的代码...

describe('ClientDeactivateComponent', () => {
  let component: ClientDeactivateComponent;
  let fixture: ComponentFixture<ClientDeactivateComponent>;

  const spyMatDialog = jasmine.createSpyObj('MatDialog', ['open']);
  const spyRouter = jasmine.createSpyObj('Router', ['navigate']);
  spyRouter.navigate.and.returnValue(Promise.resolve({}));

  const spyClientsService = jasmine.createSpyObj('ClientsService', ['deactivateClient']);
  const successDeativation = {};

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        ClientDeactivateComponent,
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      imports: [
        HttpClientModule,
        RouterTestingModule.withRoutes([{path: '**', component: ClientDeactivateComponent}])
      ],
      providers: [
        FormBuilder,
        ClientsService
      ]
    }).overrideComponent(ClientDeactivateComponent, {
        set: {
          providers: [
            {provide: Router, useValue: spyRouter},
            {provide: ClientsService, useValue: spyClientsService},
            {provide: MatDialog, useValue: spyMatDialog},
            {provide: Router, useValue: spyRouter},
            {provide: ActivatedRoute, useValue: {params: from([{id: 1}])}}
          ],
          template: '<div>Overridden template</div>'
        }
      }
    )
      .compileComponents();
  }));

  afterEach(() => {
    spyMatDialog.open.calls.reset();
    spyRouter.navigate.calls.reset();
    spyClientsService.deactivateClient.calls.reset();
    fixture.detectChanges();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(ClientDeactivateComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  describe('default', () => {
    /* this works! */
    it('should create', () => {
      expect(component).toBeTruthy();
    });

    /* Why isn't this working? */
    it('should open a modal window when confirmDeactivation is called', () => {
      component.confirmDeactivation();
      spyClientsService.deactivateClient.and.returnValue(successDeativation);
      expect(spyMatDialog.open).toHaveBeenCalledWith(ConfirmDialogComponent);
    });
  });
});

第一个测试按预期通过,但是第二个测试失败,并显示以下错误:

TypeError:无法读取未定义的属性“ componentInstance”

我在这里查看了许多答案,但尝试解决该问题的方法却无效。我确定这与测试台的加载方式有关,但我无法确定出什么问题以及为什么?

1 个答案:

答案 0 :(得分:0)

我发现了问题所在。错误消息“无法读取未定义的属性'componentInstance”使我关注

fragment dutiesSkill on Skill {
  dutiesSkill: duties {
    ...duty
  }
}

情况并非如此,我的模态spyMatDialog的模拟被错误地模拟了!下面的代码显示了如何正确模拟spyMatDialog:

component = fixture.componentInstance;