本文介绍了测试组件时如何模拟Pipe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我重载提供程序以使用这样的模拟服务:

Currently I am overriding providers to use mocked services like this:

beforeEach(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    tcb.overrideProviders(AddFieldToObjectDropdownComponent,
        [
             provide(ServiceA, { useClass: MockServiceA })),
             provide(ServiceB, { useClass: MockServiceB }))
        ])
    ...

我想对组件使用的管道做同样的事情。我试过了 provide(PipeA,{useClass:MockPipeA}) provide(PipeA,{useValue:new MockPipeA()}),但是都没有用。

I want to do same thing for pipes that the component uses. I tried, provide(PipeA, { useClass: MockPipeA }) and provide(PipeA, { useValue: new MockPipeA() }) but both didn't work.

推荐答案

您可以在声明中添加模拟对象 TestBed

TestBed.configureTestingModule({
             declarations: [
                 AppComponent,
                 MockPipe
             ],
            ...

模拟管道需要具有 @Pipe

The MockPipe needs to have the @Pipe decorator with the original name.

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

@Pipe({name: 'pipename'})
class MockPipe implements PipeTransform {
    transform(value: number): number {
        //Do stuff here, if you want
        return value;
    }
}

这篇关于测试组件时如何模拟Pipe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 22:14