角度 2 单元测试:自定义管道错误 找不到管道



我有一个名为'myPipe'的自定义管道。我得到:

找不到管道"myPipe"错误

在我的单元测试 TS 中。请求建议在我的 .spec.ts 中导入和声明的内容

这是我的 .spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { MyComponent } from './main-page-carousel.component';
describe('CarouselComponent', () => {
  let component: MyComponent ;
  let fixture: ComponentFixture<MyComponent>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
    })
    .compileComponents();
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

谢谢!

你应该能够做到这一点:

import { MyPipe } from 'here put your custom pipe path';
TestBed.configureTestingModule({
    declarations: [ MyComponentUnderTesting, MyPipe ]
})

遇到了同样的问题,并通过在我的规范中添加以下"模拟管道"来修复它:

import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'myPipe'})
class MockPipe implements PipeTransform {
    transform(value: number): number {
        // blah blah
        return value;
    }
}

然后,您必须将 MockPipe 添加到 TestBed configureTestingModule 声明中:

TestBed.configureTestingModule({
  declarations: [ MyComponentUnderTesting, MockPipe ]
})

我遇到了几乎相同的管道问题; 在模板解析错误的情况下,您需要采取两个步骤:

  1. 在开始时导入所需的管道,如下所示:

    import {{ your_pipe_name }} from '../your/pipe/location' ;

  2. 将其添加到您的声明中:

    TestBed.configureTestingModule({ declarations: [ your_pipe ] });

祝您编码愉快!

看起来你别名/命名了你的管道,但没有人基于此回答。例如,如果管道名为myCustomPipe,但这与管道的类名不同:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'myCustomPipe',
  pure: false
})
export class MyPipe implements PipeTransform {
    // ....
}

然后在spec.ts文件中,您可以按如下方式导入管道,否则将找不到它:

import { MyPipe as myCustomPipe } from 'path/to/pipe';

在您的beforeEach()中,您需要将别名引用为declarationprovider

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [ ... ],
        declarations: [ myCustomPipe, etc],
        providers: [ myCustomPipe, etc ]
    }).compilecomponents();
    // etc
});

你应该开始类似的东西

import { TestBed, async } from '@angular/core/testing';
import { MyPipe } from 'here put your custom pipe path';
describe('Pipe: MyPipe', () => {
  it('create an instance', () => {
    let pipe = new MyPipe();
    expect(pipe).toBeTruthy();
  });
});

最新更新