TypeError: this.oktaAuth.getUser is not a function .Unit test cases failing when using Okta library in angular

I am Using okta library for my authentication in angular8 .So far the functionalities are working fine but the project requirement is to write unit test cases in angular8. Below is my code for the service component and spec file.

I am creating one common service (AccessCheck service) where I am checking user access from okta library and returning the result to component. Using that result I am making api calls in my application. When I run the app functionality is working fine.

But when I run the basic setup of unit test in angular it fails at service call of okta and give error okta get user is not a function. I am not sure how to write test cases for third party library in angular. Any help will be appreciated

My Code

Access-CheckService.ts

@Injectable({
    providedIn: 'root'
})

export class AccessCheckService {

constructor(private router: Router,

        private oktaAuth: OktaAuthService, private commonService: CommonService) { }
 
async checkUserAcess() {
        let userAccess = {
            adminFlag: false,
            isOnlyuserRole: false
        }
        await this.oktaAuth.getUser().then((user) => {
       localStorage.setItem("userAcces", JSON.stringify(userAccess))
        return userAccess
})

async checkAdGroupsandProjectIds() {
        let projectDetails = JSON.parse(localStorage.getItem('ProjectDetails'))
        let userRole = JSON.parse(localStorage.getItem('userAcces'))
        if (!userRole) {
            userRole = await this.checkUserAcess()
        }
       let obj = {
            projectIds: projectDetails ,
            isOnlyuserRole: userRole 
        }
        return obj
    }

JobDetials.component.ts

export class JobDetailsComponent implements OnInit {

constructor(private jobDetailsService: JobDetailsService, private formBuilder: FormBuilder, private route: ActivatedRoute, 
    private commonService: CommonService,private router: Router,
    private accessCheck:AccessCheckService) { }

async ngOnInit() {   

    let userRoles = await this.accessCheck.checkAdGroupsandProjectIds()
    this.route.paramMap.subscribe(params => {
      this.details_id = params.get("id")    
    });


  if(!userRoles.isOnlyuserRole){
    this.getJobDetails(this.details_id,userRoles.projectIds,userRoles.isAdminFlag);
  }
}
 

JobDetails.component.spec.ts

describe('JobDetailsComponent', () => {

  let component: JobDetailsComponent;
  let fixture: ComponentFixture<JobDetailsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [JobDetailsComponent],
      imports: [RouterTestingModule, MaterialModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, HttpClientTestingModule,MatSnackBarModule],

      schemas: [ NO_ERRORS_SCHEMA ],

      providers: [{ provide: OktaAuthService, useValue: environment },AccessCheckService]
    })
      .compileComponents();
  }));

  beforeEach(() => {

    fixture = TestBed.createComponent(JobDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges()
  });

  it('should have job details component', () => {
    expect(component).toBeTruthy();
  });

  it('should have a title', () => {
    const compiled = fixture.nativeElement;
    fixture.detectChanges();                               /// failing here
    expect(compiled.querySelector('.title-container .title').textContent).toContain('Job Details:');
});

 

enivironment.ts

export const environment = {

  oktaIssuer: 'https://identity.mycompany.net',
  // oktaRedirectUrl: 'https://mycompany.net/signin',
  oktaRedirectUrl: 'http://localhost:4200/signin',
  oktaClientId: '1234Id',
  production: false
};


I am getting error like below for every test case written in spec file

TypeError: this.oktaAuth.getUser is not a function
TypeError: this.oktaAuth.getUser is not a function
    at AccessCheckService.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/services/accesscheck.service.ts:24:29)
 

If I change the providers array in spec file to

schemas: [ NO_ERRORS_SCHEMA ],

      providers: [OktaAuthService,AccessCheckService]

Then error changes to

your okta url is missing. you can copy your domain from the okta developer console

Source: Angular Questions

One Reply to “TypeError: this.oktaAuth.getUser is not a function .Unit test cases failing when using Okta library in angular”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.