我开始编写单元测试,但遇到了一些问题。
测试失败并出现错误
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();
});
});
答案 0 :(得分:1)
那是因为您还需要设置候选输入以及其他输入,
it('should create', () => {
expect(component).toBeTruthy();
component.isAdmin = mockIsAdmin;
component.birthday = mockBirthday;
component.candidate = mockCandidate; // here
fixture.detectChanges();
});