【问题标题】:Jest: Cannot set property ' ' of undefined (Angular)笑话:无法设置未定义的属性“”(Angular)
【发布时间】:2020-08-03 17:19:36
【问题描述】:

我开始编写单元测试并且遇到了一些问题。 测试失败并出现错误 TypeError: Cannot set property 'birthday' of undefined

也许有人可以建议如何使其正常工作。 非常感谢您的帮助!

我的代码:

CandidateItemComponent.ts

export class CandidateItemComponent implements OnInit {

  @Input() candidate: Candidate;
  @Input() isAdmin: boolean;
  birthday: string;

  ngOnInit() {
    this.birthday = this.candidate.birthday;
  }
}

CandidateItemComponent.html

<div *ngFor="let property of visibleCandidateProperties"
     class="candidate-item"
     [attr.title]="property.propertyKey === 'age' ? birthday : ''">
  {{candidate[property.propertyKey]}}
</div>

CandidateItemComponent.spec.ts

import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { CandidateItemComponent } from './candidate-item.component';

describe('CandidateItemComponent', () => {
  let component: CandidateItemComponent;
  let fixture: ComponentFixture<CandidateItemComponent>;
  const mockIsAdmin = true;
  const mockBirthday = '12-07-1997';

  const mockCandidate = {
    id: 2,
    firstName: 'Alexander',
    lastName: 'Osichanskiy',
    email: 'sashaoles1727@gmail.com',
    phone: '380638732626',
    birthday: '12-07-1997',
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [CandidateItemComponent],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CandidateItemComponent);
    component = fixture.debugElement.componentInstance;
    component.isAdmin = mockIsAdmin;
    component.birthday = mockBirthday;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

【问题讨论】:

    标签: angular unit-testing jestjs


    【解决方案1】:

    那是因为您还需要将 candidate 输入与其他输入一起设置,

    it('should create', () => {
        expect(component).toBeTruthy();
        component.isAdmin = mockIsAdmin;
        component.birthday = mockBirthday;
    
        component.candidate = mockCandidate;         // here
    
        fixture.detectChanges();
      });
    

    【讨论】:

      猜你喜欢
      • 2015-12-07
      • 2018-10-29
      • 2019-04-20
      • 2021-10-29
      • 1970-01-01
      • 2018-06-28
      • 2021-10-26
      • 2019-05-08
      • 2021-11-27
      相关资源
      最近更新 更多