1

我如何模拟 angular-auth-oidc-client 以使用 karma-jasmine 返回一些假令牌。下面是我需要编写单元测试用例的代码。

getToken() {
    return this.oidcSecurityService.getToken();
}
4

2 回答 2

1

这是我的文章,它涵盖了所有这些基本测试场景还有一篇文章专门谈到了这个案例。随时提供您的反馈

您需要创建一个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} ]
  });

于 2019-07-26T05:44:48.680 回答
0

我假设您正在测试一个组件。您可以尝试这里提到的方法: 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');
});
于 2019-07-25T11:17:33.607 回答