【发布时间】:2021-01-01 00:20:25
【问题描述】:
谁能告诉我如何为下面的语句编写单元测试?!
localStorage.getItem('token') ? (this.isAuthenticated = true) : (this.isAuthenticated = false);
提前谢谢你!
【问题讨论】:
标签: angular typescript unit-testing if-statement conditional-statements
谁能告诉我如何为下面的语句编写单元测试?!
localStorage.getItem('token') ? (this.isAuthenticated = true) : (this.isAuthenticated = false);
提前谢谢你!
【问题讨论】:
标签: angular typescript unit-testing if-statement conditional-statements
您可以在测试提供程序中添加 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();
}
【讨论】:
您可以模拟对 localStorage.getItems 的调用。在第一个测试中,让它返回一个令牌并检查 isAuthenticated 是否为真。然后让它返回一个假值并检查 isAuthenticated 是否为假。
【讨论】: