[英]How to unit test a function with a dependency (angular)
我是單元測試的新手,並且有一些基礎知識。 但是,我正在嘗試測試一種方法。 此方法調用一個函數,該函數是oidc-client.js的一部分。 它基本上簽署了用戶。
spec文件
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AuthCallbackComponent } from './auth-callback.component';
import { RouterTestingModule } from '@angular/router/testing';
fdescribe('AuthCallbackComponent', () => {
let component: AuthCallbackComponent;
let fixture: ComponentFixture<AuthCallbackComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [ AuthCallbackComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AuthCallbackComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
component.ts
import { UserManager,User,UserManagerSettings,WebStorageStateStore} from 'oidc-client';
manager = new UserManager(this.getClientSettings());
ngOnInit() {
this.authService.completeAuthentication();
}
completeAuthentication(): Promise<void> {
return this.manager.signinRedirectCallback().then(user => {
this.user = user;
this.router.navigate(['/']);
this.setUser.next(this.user.profile);
this.onLogin.next(true)
});
}
getClientSettings() {
return {
authority: environment.authority,
client_id: environment.client_id,
redirect_uri: environment.login,
post_logout_redirect_uri: environment.logout,
response_type: 'code',
scope: 'openid profile email phone address',
filterProtocolClaims: true,
loadUserInfo: false,
accessTokenExpiringNotificationTime: 60,
silentRequestTimeout: 10000,
includeIdTokenInSilentRenew: true,
automaticSilentRenew: true,
silent_redirect_uri: environment.silent_redirect
};
}
}
我不確定如何測試這個。 當我進行測試時,我得到了“沒有回應狀態”。 我希望測試通過,也許有關如何測試completeAuthentication()的一些想法
用於測試無法控制的代碼的一個工具是Sinon的stub
對象 ,它可以讓您模擬第三方依賴項的所需行為。
如果沒有看到您嘗試測試的源代碼,那么問題就沒那么多了,但我希望Sinon項目中的示例文檔足以滿足您的使用需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.