Angular Unit Test should create FAILED TypeError: Cannot read properties of undefined (reading 'preferences')

Angular Unit Test should create FAILED TypeError: Cannot read properties of undefined (reading 'preferences')

我正在尝试创建覆盖所有行 (Jasmine / Karma) 但我收到错误消息 无法读取 属性 'preferences' of undefined

这是我的组件代码。

    export class PreferComponent implements OnInit {
  @Output() updatePreferences = new EventEmitter<any>();
  @ViewChild('settingModal', { static: true }) settingModal: any;
  private data: any;
  preferences = [];
  maxCols: number;
  selectedPref: number;
  constructor() { }

  ngOnInit(): void {
    this.preferences = JSON.parse(JSON.stringify(this.data.preferences));
    this.maxCols = this.data.maxCols;
    this.selectedPref = this.data.selectedPref;
    this.checkPreferences();
  }

  setPreferences(col, val) {
    if (val) {
      col.isPreferredColumn = true;
      this.selectedPref++;
    } else {
      col.isPreferredColumn = false;
      this.selectedPref--;
    }
    this.checkPreferences();
  }
}

下面是我试过的规格代码:

   fdescribe('PreferComponent ', () => {
  let component: PreferComponent ;
  let fixture: ComponentFixture<PreferComponent >;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [PreferencesComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]

    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(PreferComponent );
    fixture.detectChanges();

    component = fixture.componentInstance;
    const data1 = {
      preferences: [1, 2, 4],
      "maxCols": 5,
      "selectedPref": 7
    };
    component.preferences = data1.preferences;
    component.maxCols = data1.maxCols;
    component.selectedPref = data1.selectedPref;
    expect(component.preferences).toEqual([1, 2, 4]);

    component.ngOnInit();
  });
});

我这里做错了什么?

ngOnInit 方法中,您正在为 this.preferences 分配一个从 this.data.

获得的值

因此,在beforeEach函数中,应作如下改动:

而不是...

component.preferences = data1.preferences;

...这样写:

@ts-ignore
component.data = data1;

Further you should move expect(component.preferences).toEqual([1, 2, 4]); after component.ngOnInit(); since this checks if ngOnInit did what you expected it to do.