【问题标题】:Unit Test in Angular for async logout functionAngular中用于异步注销功能的单元测试
【发布时间】:2021-10-04 19:25:08
【问题描述】:

我是 Angular 的新手,并试图为它创建单元测试。在我的 component.ts 中,我有这样的代码

  async doLogout() {
    const idUser = parseInt(this.authService.getUserData.id, 10);
    this.authService.setRedirectUrl('');
    this.router.navigate(['auth/login'], { state: { isLogout: true } });
  }

不在这里,我有点困惑如何在 component.spec.ts 中编写它。我试着这样写:

let routerSpy = {navigate: jasmine.createSpy('navigate')};

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [ HeaderComponent ],
      imports: [
        RouterTestingModule,
        ApolloTestingModule,
        MatDialogModule,
        HttpClientTestingModule,
        MatSnackBarModule,
        AngularFireModule.initializeApp(firebaseconf),
        AngularFireMessagingModule,
        AngularFireAuthModule,
        MatDialogModule,
        BrowserAnimationsModule
      ],
      providers: [
        { provide: MessagingService, useClass: MessagingServiceMock },
        { provide:ThemeService, useClass: ThemeServiceMock },
        { provide: NotificationService, useClass: NotificationServiceMock },
        { provide: GetAvailableGroupListUsecase, useClass: GetAvailableGroupListUsecaseMock }, 
        { provide: Router, useValue: routerSpy }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents()
  }));

it('async doLogOut', fakeAsync(() => {
component.doLogOut()
expect(routerSpy.navigate).toHaveBeenCalledWith(['/auth/login']);
}))

我错过了什么?你的帮助对我来说意义重大

【问题讨论】:

  • 你有什么错误吗?
  • 是的,错误消息是:错误:预期的间谍导航已被调用:[['/auth/login']],但从未调用过。 @ammadkh
  • 提供的代码未显示您如何创建component。请使用所有相关代码部分更新问题。
  • 更新@PhilippMeissner
  • 仍然缺少您分配 component 的代码:D

标签: javascript angular unit-testing jestjs jasmine


【解决方案1】:

async 与该方法无关,我会删除它,看看它是否在没有 async 的情况下工作,因此您不必等待任何承诺。

试试这个:

 doLogout() {
    const idUser = parseInt(this.authService.getUserData.id, 10);
    this.authService.setRedirectUrl('');
    this.router.navigate(['auth/login'], { state: { isLogout: true } });
  }
.....
it('async doLogOut', () => {
  component.doLogOut()
  expect(routerSpy.navigate).toHaveBeenCalledWith(['/auth/login']);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    相关资源
    最近更新 更多