单元测试角度

时间:2020-09-14 09:25:25

标签: angular typescript unit-testing if-statement conditional-statements

有人可以告诉我如何为以下语句编写单元测试吗?!

localStorage.getItem('token') ? (this.isAuthenticated = true) : (this.isAuthenticated = false);

提前谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在测试提供程序中添加LocalStorage并模拟其内容:

providers: [
  {
    provide: LocalStorageService, 
    useValue: {
      getItem: () => true
    }
  }
]

,然后在您的单元测试中:

it('should set Authenticated to true', () => {
  // call your function
  expect(component.isAuthenticated).toBeTrue();
}

如果您希望它返回false:

it('should set Authenticated to false', () => {
  TestBed.get(LocalStorageService, 'getItem').and.returnValue(false);
  // call your function
  expect(component.isAuthenticated).toBeFalse();
}

答案 1 :(得分:0)

您可以模拟对localStorage.getItems的调用。在第一个测试中,使其返回令牌并检查isAuthenticated为true。然后使它返回一个伪造的值,并检查isAuthenticated是否为假。