在服务测试中使用MockPipe模拟管道

问题描述 投票:1回答:1

我有一个具有这样的构造函数的服务:

constructor(
    private store: Store<any>,
    private decimalPipe: DecimalPipe
) {}

现在,我想在测试中模拟DecimalPipe,因为这不是我要测试的东西,在进行模拟尝试之前,我将其用于工作测试:

const createService = createServiceFactory({
    service: MyInvestmentCommonService,
    imports: [TestingModule],
    providers: [
      DecimalPipe,
      ClassificationFilterHelper,
    ],
});

但是当我将其更改为:

const createService = createServiceFactory({
    service: MyInvestmentCommonService,
    imports: [TestingModule],
    providers: [
      MockPipe(DecimalPipe),
      ClassificationFilterHelper,
    ],
});

我收到错误:

error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'MyInvestmentCommonService', Function ] })
Error: StaticInjectorError(DynamicTestModule)[MyInvestmentCommonService -> DecimalPipe]: 
  StaticInjectorError(Platform: core)[MyInvestmentCommonService -> DecimalPipe]: 
    NullInjectorError: No provider for DecimalPipe!

我在这里做错了什么?

angular mocking angular-pipe angular-testing
1个回答
0
投票

您应该使用真实管道的名称为测试套件创建一个模拟管道,然后为TestBed声明它。类似于:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'name-of-the-original-pipe'})      // <-- this is important!!
class DecimalPipeMock implements PipeTransform {
    transform(value: number): number {
        // ... do any mock transformation here if needed
        return value;
    }
}

// .... and declared it in the TestBed

TestBed.configureTestingModule({
  declarations: [
    ...
    DecimalPipeMock
  ],
...
});
© www.soinside.com 2019 - 2024. All rights reserved.