如何使用karma-jasmine模拟angular-auth-oidc-client返回一些假令牌?下面是我编写单元测试用例所需的代码。
getToken() {
return this.oidcSecurityService.getToken();
}发布于 2019-07-26 13:44:49
从Here is my article which covers all such basic testing scenarios开始。There is another article which specifically talks about this case。随时提供您的反馈
您需要创建一个模拟oidcSecurityService行为的stub,
export class OidcSecurityServiceStub{
getToken(){
return 'some_token_eVbnasdQ324';
}
// similarly mock other methods "oidcSecurityService" as per the component requirement
}然后在spec文件中,在TestBed中使用useClass,如下所示
TestBed.configureTestingModule({
declarations: [ WhateverComponent],
providers: [ {provide: OidcSecurityService(or whatever the name is), useClass: OidcSecurityServiceStub} ]
});发布于 2019-07-25 19:17:34
我假设你在测试一个组件。您可以尝试这里提到的方法: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');
});https://stackoverflow.com/questions/57199468
复制相似问题