2

How can i mock angular-auth-oidc-client to return some fake token using karma-jasmine. Below is the code that i need to write a unit test case.

getToken() {
    return this.oidcSecurityService.getToken();
}
Aravind
  • 53
  • 3
  • 10

2 Answers2

2

Here is my article which covers all such basic testing scenarios to start with. There is another article which specifically talks about this case. Feel free to provide your feedback

You'll need to create a stub which will mock the behavior of oidcSecurityService,

export class OidcSecurityServiceStub{
   getToken(){
      return 'some_token_eVbnasdQ324';
   }
   // similarly mock other methods "oidcSecurityService" as per the component requirement

}

then in spec file, use useClass as below in TestBed:

TestBed.configureTestingModule({
     declarations: [ WhateverComponent],
     providers:    [ {provide: OidcSecurityService(or whatever the name is), useClass: OidcSecurityServiceStub} ]
  });

Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
0

I'm assuming you're testing a component. You could try the method mentioned here: https://angular.io/guide/testing#final-setup-and-tests.

Edit and excerpt from the site:

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');
});
Eli
  • 1,670
  • 1
  • 20
  • 23
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/23624231) – ρяσѕρєя K Jul 25 '19 at 11:52
  • 1
    Hi I updated my answer with the code. Could you verify it meets the standards please? Thanks. – Eli Jul 25 '19 at 12:23
  • @Eli : The answer you have provided is not exactly what the user has asked. Its really great that u are improving it. You can refer my answer. Your answer has more code with not much attention to exact thing required. Please take my suggestions as a friend and not as a critic to grow on Stackoverflow :) . Cheers mate ! – Shashank Vivek Jul 26 '19 at 05:52