1

我使用 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;
}

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

谢谢你的帮助。

4

1 回答 1

1

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

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');
  });
});
于 2021-01-24T09:56:25.393 回答