TypeError:this.oktaAuth.getUser不是函数.在angular中使用Okta库时,单元测试用例



我正在angular8中使用okta库进行身份验证。到目前为止,功能运行良好,但项目要求是在angular 8中编写单元测试用例。下面是我的服务组件和规范文件的代码。

我正在创建一个通用服务(AccessCheck服务(,在这里我检查okta库中的用户访问,并将结果返回到组件。使用这个结果,我在我的应用程序中进行api调用。当我运行应用程序时,功能运行良好。

但当我在angular中运行单元测试的基本设置时,它在okta的服务调用时失败,并给出错误okta get user不是一个函数。我不知道如何在angular中为第三方库编写测试用例。如有任何帮助,将不胜感激

我的代码

访问检查服务.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:');
});

环境.ts

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

对于规范文件中编写的每个测试用例,我都会收到如下错误

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)

如果我将规范文件中的提供者阵列更改为

schemas: [ NO_ERRORS_SCHEMA ],
providers: [OktaAuthService,AccessCheckService]

然后错误变为

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

我知道这个问题很老了,但我想我会为将来查找这个问题的人回答这个问题。解决这个问题的方法是添加OktaAuth作为提供者,并使用Jasmin间谍模拟get用户调用,如下所示:

{
provide: OKTA_AUTH,
useFactory: () => {
const mockService = jasmine.createSpyObj('OktaAuth', ['getUser']);
mockService.getUser.and.callFake(() => Promise.resolve({ name: 'Test' }));
return mockService;
}
}

只需将其添加到单元测试提供程序数组中,就可以开始了。

相关内容

最新更新