2

我构建了一个小型 Angular 应用程序,现在我正在编写单元测试。到目前为止一切都很好,但是当我尝试测试我的 authGuard 时遇到了一些问题。我正在使用观众。我在规范的提供程序部分提供了 platformId,但我希望能够覆盖它,以便我可以测试值“服务器”和“浏览器”的场景我的代码用于 authGuard:

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(
    private authService: AuthService,
    private router: Router,
    @Inject(PLATFORM_ID) private platformId: Object,
  ) {}

  canActivate(
    _route: ActivatedRouteSnapshot,
    _state: RouterStateSnapshot,
  ): boolean | UrlTree | Promise<boolean | UrlTree> | Observable<boolean | UrlTree> {
    if (isPlatformServer(this.platformId)) {
      console.log('server');
      return true;
    } else {
      console.log('browser');
      this.authService.autoLogin();
      return this.authService.user.pipe(
        take(1),
        map((user) => {
          console.log('user', user);
          if (!!user) {
            return true;
          }
          console.log('navugate');
          this.router.navigate(['/auth']);
          return false;
        }),
      );
    }
  }
}

和规范文件:

describe('AuthGuard', () => {
  let spectator: SpectatorService<AuthGuard>;
  const config = {
    service: AuthGuard,
    imports: [RouterTestingModule, HttpClientTestingModule],
    providers: [AppRoutingModule, AuthService, { provide: PLATFORM_ID, useValue: 'server' }],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
  };
  const createService = createServiceFactory(config);

// some other tests here ....

  it('should should navigate to /auth if running on browser and not authenticated', () => {
    config.providers = [AppRoutingModule, { provide: PLATFORM_ID, useValue: 'browser' }];
    spectator = createService();
    const spyNavigate = spyOn(spectator.service['router'], 'navigate').and.callThrough();
    const user = new User('bla@bla.com', 'id', 'token', new Date(10000));
    spectator.service['authService'].user.next(user);
    spectator.service.canActivate(null, null);
    expect(spyNavigate).toHaveBeenCalled();
  });
});

现在,当我运行此覆盖时,配置不起作用。这是意料之中的,因为配置对象在更改之前已经传递。但是如何实现我的目标?我试过这个:

describe('AuthGuard', () => {
  let spectator: SpectatorService<AuthGuard>;
  const config = {
    service: AuthGuard,
    imports: [RouterTestingModule, HttpClientTestingModule],
    providers: [AppRoutingModule, AuthService, { provide: PLATFORM_ID, useValue: 'server' }],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
  };

// some other tests here ....

  it('should should navigate to /auth if running on browser and not authenticated', () => {
    config.providers = [AppRoutingModule, { provide: PLATFORM_ID, useValue: 'browser' }];
    const createService = createServiceFactory(config);
    spectator = createService();
    const spyNavigate = spyOn(spectator.service['router'], 'navigate').and.callThrough();
    const user = new User('bla@bla.com', 'id', 'token', new Date(10000));
    spectator.service['authService'].user.next(user);
    spectator.service.canActivate(null, null);
    expect(spyNavigate).toHaveBeenCalled();
  });
});

但这给了我一个Error: 'beforeEach' should only be used in 'describe' function令人困惑的错误,因为我没有在本规范中使用 beforeEach。

我觉得像 Spectator 这样的工具可能应该有一个简单的方法来做到这一点,它不是那么奇特,对吧?

任何帮助表示赞赏!

4

1 回答 1

1

您可以通过将参数传递给createService()

createService({
  providers: [...]
});

于 2021-07-13T11:52:39.597 回答