【问题标题】:AuthGuard Error: Cannot call Promise.then from within a sync testAuthGuard 错误:无法从同步测试中调用 Promise.then
【发布时间】:2021-02-23 17:16:54
【问题描述】:

我尝试在 Angular 10 中测试一个保护组件。该组件已注入服务

错误消息:“错误:无法从同步测试中调用 Promise.then。”。也许有人知道出了什么问题?

    import { TestBed, waitForAsync, async, getTestBed } from '@angular/core/testing';
import { AngularFireModule } from '@angular/fire';
import { AuthGuard } from './auth.guard';
import { AuthService } from '../shared/services/auth.service';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { environment } from '../../environments/environment';

describe('AuthGuard', () => {
  let guard: AuthGuard;
  let injector: TestBed;
  let authService: AuthService;
  const routerMock = {navigate: jasmine.createSpy('chats')};

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AuthGuard, { provide: Router, useValue: routerMock }],
      imports: [
        HttpClientTestingModule,
        AngularFireModule.initializeApp(environment.firebaseConfig)
      ]
    }).compileComponents();
    guard = TestBed.inject(AuthGuard);
  });

  injector = getTestBed();
  authService = injector.inject(AuthService);
  guard = injector.inject(AuthGuard);

  it('should be created', () => {
    expect(guard).toBeTruthy();
  });


  it('should redirect an unauthenticated user to the login route', waitForAsync(() => {
    const promise = new Promise(() => {});
    promise.then(() => {
        expect(authService.SignOut).toBeTruthy();
    });
  }));

  it('should allow the authenticated user to access app', waitForAsync(() => {
    const promise = new Promise(() => {});
    promise.then(() => {
        expect(authService.isLoggedIn).toBe(true);
    });
  }));
});

你能帮我吗?谢谢

【问题讨论】:

    标签: angular typescript unit-testing


    【解决方案1】:

    简而言之:您应该将 routerMock 的初始化移动到 beforeEach() 块中。

    这个问题已经讨论过了: Unit test error: Cannot call Promise.then from within a sync test

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 1970-01-01
      • 2019-11-11
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 2021-04-08
      • 2018-03-26
      相关资源
      最近更新 更多