如何在 SpectatorRouting 中提供服务模拟

问题描述

我使用 spectator 对 Angular 组件进行了测试。尝试使用 spectatorRouting 找到模拟服务的解决方案。我有如下简单的服务:

export class ProductService {
  constructor(private http: HttpClient) {}

  getProduct(productId: string): Observable<Product>;
}

我有如下组件:

export class ProductComponent {
  product$: Observable<boolean | Product>;

  readonly routes = routes;

  constructor(
    private route: ActivatedRoute,private productService: ProductService,private router: Router
  ) {

    this.product$ = this.route.paramMap.pipe(
      map((params) => params.get('id')),switchMap((val) => productService.getProduct(val)),catchError(() => this.router.navigate([routes.notFoundPage]))
    );
  }
}

而且我找不到通过模拟 ProductService 方法返回值的漂亮解决方案。我实施了一个解决方案,但这很难看:(.

const productService = {
  getProduct: () => of({}),};

describe('ProductComponentspectator',() => {
  let spectator: spectatorRouting<ProductComponent>;
  const createComponent = createRoutingFactory({
    component: ProductComponent,params: { id: '100' },declarations: [
      MainProductComponent,DetailsProductComponent,SpanTooltipComponent,],imports: [HttpClientTestingModule,RouterTestingModule],providers: [mockProvider(ProductService,productService)],});

  beforeEach(() => {
    spyOn(productService,'getProduct').and.returnValue(of(getProduct()));
    spectator = createComponent();
  });

  it('should get brand name',() => {
    expect(spectator.query('.product-brand')).toHaveExactText('Asus');
  });
});

function getProduct(): Product {
  return {
    productId: '100',brand: 'Asus',} as Product;
}

我对这个解决方案有疑问,对我来说,在测试之上创建 const 服务和下一个 spyOn 相同的方法是一种奇怪的方法。我的直觉告诉我,这个模拟应该在提供者中完全定义(使用方法等)。 spectator 可能为 spectatorRouting 提供了更友好的 mocking 服务,但我没有找到。

感谢您的帮助。

解决方法

如果你想模拟它 - 你可以另外安装 ng-mocks 包,那么你就不需要 spyOngetProduct

describe('ProductComponentSpectator',() => {
  let spectator: SpectatorRouting<ProductComponent>;
  const createComponent = createRoutingFactory({
    component: ProductComponent,params: { id: '100' },declarations: [
      MainProductComponent,DetailsProductComponent,SpanTooltipComponent,],imports: [HttpClientTestingModule,RouterTestingModule],providers: [
      // MockProvider from ng-mocks (capital M)
      MockProvider(ProductService,{
        getProduct: () => of({
          productId: '100',brand: 'Asus',} as Product),}),});

  beforeEach(() => {
    spectator = createComponent();
  });

  it('should get brand name',() => {
    expect(spectator.query('.product-brand')).toHaveExactText('Asus');
  });
});