我如何模拟 angular-auth-oidc 客户端到 return 假数据

How can i mock angular-auth-oidc client to return fake data

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

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

我假设您正在测试一个组件。 你可以试试这里提到的方法: 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');
});

Here is my article which covers all such basic testing scenarios to start with. There is another article which specifically talks about this case。欢迎提供您的反馈

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