【问题标题】:Spectator: override provider for single test (angular universal)观众:单一测试的覆盖提供者(角度通用)
【发布时间】:2021-06-03 12:20:27
【问题描述】:

我构建了一个小型 Angular 应用程序,现在我正在编写单元测试。到目前为止一切顺利,但是当我尝试测试我的 authGuard 时遇到了一些问题。我正在使用Spectator。 我在规范的提供者部分提供了 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 这样的工具应该有一个简单的方法来做到这一点,它不是那么奇特,对吧?

感谢任何帮助!

【问题讨论】:

    标签: angular angular-universal angular-unit-test spectator


    【解决方案1】:

    您可以通过将参数传递给 createService() 来做到这一点:

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

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 2020-06-28
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多