单元测试没有通过,尽管它显然应该通过?

Unit test does not pass even though it obviously should?

我想测试一个简单的函数,但是没有出现明显的结果...

我的函数如何工作(实际上它确实有效,只是没有正确测试)

  1. 我将一个字符串传递到我的函数中
  2. 如果它与我的数组中的一个元素匹配
    1. Returns 字符串
  3. 如果它与我的数组中的元素不匹配
    1. returns 字符串 'default'

当我 运行 测试显示时,我收到错误:

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');
  });

我认为您在循环中使用 const 是问题所在。您应该在此处使用 let,因为使用 const 可防止在循环进行时重新分配值。

isStatusExceptional(currentStatus): string {
    for (let status of this.exceptionalRaceStatuses) {
      if (status.name === currentStatus) {
        return currentStatus;
      }
    }
    return 'default';
  }

Typescript docs似乎同意这一点。

这种情况尽量不要使用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';
}