gpt4 book ai didi

Angular 7 - 通过订阅对可观察对象进行单元测试

转载 作者:行者123 更新时间:2023-11-28 21:15:37 25 4
gpt4 key购买 nike

您好,我正在尝试为具有可观察对象的组件编写 Angular 代码,但我无法测试订阅功能。我应该如何访问订阅功能?任何帮助,将不胜感激。谢谢。

这是我的可观察组件:

  ngOnInit(): void {

if (this.authService.getUser() !== null || this.authService.getUser() !== undefined) {
console.log('getUser');
this.userService.userDetails = this.authService.getUser();
}

if (this.environmentName === 'QA' || this.environmentName === 'LOCAL' || this.environmentName === 'QA-STAGING') {
console.log('environmentName');
this.authService.acquireTokenSilent(['api://012fdc3a-c966-4312-9b5c-301f097c1803/server']);
} else {
this.authService.acquireTokenSilent(['api://58a80bb5-906b-4ec0-9b41-7a78a07125af/server']);
}

this.subscription.add(
this.broadcastService.subscribe('msal:acquireTokenSuccess', (payload) => {
// do something here
console.log('acquire token success ' + JSON.stringify(payload));

this.roleService.checkServerEventReviewers().subscribe(res => {
this.userService.userDetails.role = res ? 'Data Steward' : 'Mosaic Consumer';
if (this.isLoggedIn !== true) {
const redirectUri = sessionStorage.getItem('redirectUri');
if (redirectUri !== undefined || redirectUri !== null) {
this.router.navigateByUrl(redirectUri);
}
}
this.isLoggedIn = true;
};

这是我正在尝试的规范文件:

describe('AppComponent', () => {
beforeEach(() => {
let subscription: Subscription = new Subscription();
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent],
providers: [WindowService, RoleService, HttpClient, HttpHandler, BroadcastService, MsalService,
{
provide: MSAL_CONFIG, // MsalService needs config, this provides it.
useFactory: () => ({ // Note this is an arrow fn that returns the config object
redirectUri: window.location.origin + '/',
clientID: mockData.clientID,
}),
}],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
});

describe(':', () => {
function setup() {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
const compiled = fixture.debugElement.nativeElement;
return {fixture, app, compiled};
}

it('Init with QA environment', () => {
const {app} = setup();
spyOn(app.authService, 'getUser').and.returnValue(mockData.userDetails);
spyOn(app.authService, 'acquireTokenSilent').and.returnValue('msal:acquireTokenSuccess');
app.ngOnInit();
app.subscription.add(
app.broadcastService.subscribe('msal:acquireTokenSuccess', () => {
// do something here
});
);

最佳答案

这不是对您问题的直接回答,而是间接回答。在您的组件中包含所有这些业务逻辑可能不是什么好主意。我建议使用库来协助您进行所有状态管理(我们使用 NgRX )。然后可以将许多此类逻辑移至服务或其他更易于测试的纯方法中。

关于Angular 7 - 通过订阅对可观察对象进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58820327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com