【发布时间】:2021-01-29 15:35:06
【问题描述】:
我在 Angular 中使用 Jasmine 进行单元测试。我正在使用 OidcSecurityService 服务来确保安全。现在我想对这部分进行单元测试以实现自动登录:
export class AppComponent implements OnInit {
title = 'cityflows-client';
constructor(public oidcSecurityService: OidcSecurityService, private router: Router, public platform: Platform) {}
ngOnInit() {
this.oidcSecurityService
.checkAuth()
.subscribe(isAuthenticated => {
if (!isAuthenticated) {
if ('/autologin' !== window.location.pathname) {
this.write('redirect', window.location.pathname);
this.router.navigate(['/autologin']);
}
}
if (isAuthenticated) {
this.navigateToStoredEndpoint();
}
});
}
所以单元测试看起来像这样:
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
providers: [ {provide: OidcSecurityService, useClass: OidcSecurityServiceStub} ],
declarations: [
AppComponent
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create the app', () => {
expect(component).toBeTruthy();
});
});
存根看起来像这样:
export class OidcSecurityServiceStub {
getToken() {
return 'some_token_eVbnasdQ324';
}
checkAuth(url: string) {
return of(url);
}
authorize(authOptions?: AuthOptions) {
if (authOptions) {
return authOptions.urlHandler('http://localhost');
} else {
return null;
}
}
}
但我在报道中看到:
通过 if 表示 else 部分不被占用。
那么我必须改变什么?谢谢
it('should redirect user to login page if user is not logged in', () => {
expect(component).toBeTruthy();
});
【问题讨论】:
-
有什么建议吗?
-
我没有看到您所说的覆盖率报告图片
-
你想覆盖哪一行?你能把它圈起来以便更好地理解吗
-
是的,两个 E 都站着
标签: angular typescript unit-testing karma-jasmine istanbul