Angular 2 Unit Test:自定义管道错误找不到管道

时间:2017-01-09 07:58:20

标签: unit-testing angular

我有一个名为' myPipe'的自定义管道。我正在接受管道' myPipe'在我的单元测试中无法找到错误。

请在我的.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();
  });
});

谢谢!

4 个答案:

答案 0 :(得分:42)

你应该可以这样做:

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

答案 1 :(得分:2)

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

  1. 像开始一样导入所需的管道 “从'../your/pipe/location导入{{your_pipe_name}}“

  2. 将其添加到以下声明中: TestBed.configureTestingModule({声明:[your_pipe]});

快乐编码!!!

答案 2 :(得分:1)

我遇到了同样的问题,并通过添加以下&#34;模拟管道&#34;来修复它。我的规格:

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 ]
})

答案 3 :(得分:0)

你应该开始像

这样的事情
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();
  });
});