注入自定义管道以进行单元测试

时间:2020-04-24 11:32:47

标签: angular angular-pipe angular-test

我扩展了DecimalPipe并使用了这种方法,并且对于单元测试来说,它失败了。我也在TestBed上注册了管道。

`NullInjectorError: R3InjectorError(DynamicTestModule)[MyDecimalPipe -> MyDecimalPipe]: 
  NullInjectorError: No provider for MyDecimalPipe!

MyDecimalPipe.ts

import { DecimalPipe, registerLocaleData} from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import localeFr from '@angular/common/locales/fr';

@Pipe({
    name: 'myDecimal'
})
export class MyDecimalPipe extends DecimalPipe implements PipeTransform
{
    transform(value: any, args?: any) : any {

        registerLocaleData(localeFr);

        return super.transform(value, args, 'fr');
    }
}

MyDecimalPipe.spec.ts

import { MyDecimalPipe } from './my-decimal.pipe';
import { TestBed } from '@angular/core/testing';
import localFr from '@angular/common/locales/fr';
import { registerLocaleData, DecimalPipe } from '@angular/common'

describe('MyDecimalPipe', () => {
    let pipe: MyDecimalPipe;
    let value: number;
    let defaultLocale: string = 'en-US';

    TestBed.configureTestingModule({
        declarations:[MyDecimalPipe],
        providers:[MyDecimalPipe]
    });

    beforeEach(() => {
        value = 0;

        registerLocaleData(localFr);
        pipe = new MyDecimalPipe(defaultLocale);
    });

    it('create an instance', () => {
        //arrange

        //act

        //assert
        expect(pipe).toBeTruthy(); 
    });
})

1 个答案:

答案 0 :(得分:1)

您是否尝试删除

TestBed.configureTestingModule({
  declarations:[MyDecimalPipe],
  providers:[MyDecimalPipe]
});

我可能是错的,但是我认为您不需要它,因为您正在测试MyDecimalPipe。