我想测试一个简单的函数,但是没有出现明显的结果...
我的函数如何工作(实际上它确实有效,只是没有正确测试)
- 我将一个字符串传递到我的函数中
- 如果它与我的数组中的一个元素匹配
- 返回字符串
- 如果它与我的数组中的元素不匹配
- 返回字符串“默认”
当我运行显示的测试时,我收到错误:
Expected 'default' to equal 'hare-failure
我的组件
const state = [
{name: 'failure'}
];
isStatus(current): string {
for (const status of this.state) {
if (status.name === current) {
return current;
}
}
return 'default';
}
我的测试
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [EventComponent, ConfirmationComponent],
imports: [ReactiveFormsModule, FormsModule],
providers: []
});
fixture = TestBed.createComponent(EventComponent);
component = fixture.componentInstance;
component.ngOnInit();
}));
it('should return current status if it is part of exceptional statuses', () => {
const returned = component.isState('failure');
expect(returned).toEqual('failure');
});
最佳答案
在这种情况下尽量不要使用for-of循环。 您可以使用数组的 some() 方法重写组件,并创建一个纯函数。
所以,而不是:
isStatusExceptional(currentStatus): string {
for (const status of this.exceptionalRaceStatuses) {
if (status.name === currentStatus) {
return currentStatus;
}
}
return 'default';
写:
isStatusExceptional(current, erc = this.exceptionalRaceStatuses): string {
return erc.some(item => item.name === current) ? current : 'default';
}
关于javascript - 单元测试没有通过,尽管它显然应该通过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52277847/