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

我有一个定制的管道叫“我的管道”。我得到:

找不到管道“ myPipe”错误

在我的单元测试测试。请建议什么导入和声明在我的。规格

这是我的眼镜

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();
});
});

谢谢!

45996 次浏览

you should start something like

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();
});
});

I had the same problem, and fixed it by adding the following "mock pipe" to my spec.ts:

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


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

Then you have to add MockPipe to the TestBed configureTestingModule declarations:

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

You should be able to do this:

import { MyPipe } from 'here put your custom pipe path';


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

I had almost the same pipe issue; in cases of template parse errors, you need to take two steps:

  1. Import the required pipe at the start like:

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

  2. Add it to your declaration:

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

Happy Coding!

It looks like you aliased/named your pipe but no one is answering based on this. For example, if your pipe is named myCustomPipe but this is different than the class name for the pipe:

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


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

then in your spec.ts file you can import your pipe as follows or it will not be found:

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

and in your beforeEach() you need to reference the alias as both a declaration and a provider:

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


// etc
});