我如何模拟 angular-auth-oidc-client 以使用 karma-jasmine 返回一些假令牌。下面是我需要编写单元测试用例的代码。
getToken() {
return this.oidcSecurityService.getToken();
}
我如何模拟 angular-auth-oidc-client 以使用 karma-jasmine 返回一些假令牌。下面是我需要编写单元测试用例的代码。
getToken() {
return this.oidcSecurityService.getToken();
}
这是我的文章,它涵盖了所有这些基本测试场景。还有一篇文章专门谈到了这个案例。随时提供您的反馈
您需要创建一个stub
模拟oidcSecurityService
,
export class OidcSecurityServiceStub{
getToken(){
return 'some_token_eVbnasdQ324';
}
// similarly mock other methods "oidcSecurityService" as per the component requirement
}
然后在spec
文件中,useClass
如下使用TestBed
:
TestBed.configureTestingModule({
declarations: [ WhateverComponent],
providers: [ {provide: OidcSecurityService(or whatever the name is), useClass: OidcSecurityServiceStub} ]
});
我假设您正在测试一个组件。您可以尝试这里提到的方法: https ://angular.io/guide/testing#final-setup-and-tests 。
编辑并摘自该网站:
let userServiceStub: Partial<UserService>;
beforeEach(() => {
// stub UserService for test purposes
userServiceStub = {
isLoggedIn: true,
user: { name: 'Test User'}
};
TestBed.configureTestingModule({
declarations: [ WelcomeComponent ],
providers: [ {provide: UserService, useValue: userServiceStub } ]
});
fixture = TestBed.createComponent(WelcomeComponent);
comp = fixture.componentInstance;
// UserService from the root injector
userService = TestBed.get(UserService);
// get the "welcome" element by CSS selector (e.g., by class name)
el = fixture.nativeElement.querySelector('.welcome');
});