Si *_*Thu 28 unit-testing angular
我有一个名为'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();
});
});
Run Code Online (Sandbox Code Playgroud)
谢谢!
Jon*_*ola 55
你应该能够做到这一点:
import { MyPipe } from 'here put your custom pipe path';
TestBed.configureTestingModule({
declarations: [ MyComponentUnderTesting, MyPipe ]
})
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的问题,并通过在我的 spec.ts 中添加以下“模拟管道”来修复它:
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'myPipe'})
class MockPipe implements PipeTransform {
transform(value: number): number {
// blah blah
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你必须将 MockPipe 添加到 TestBed configureTestingModule 声明中:
TestBed.configureTestingModule({
declarations: [ MyComponentUnderTesting, MockPipe ]
})
Run Code Online (Sandbox Code Playgroud)
我有几乎相同的管道问题;在模板解析错误的情况下,您需要采取两个步骤:
在开始时导入所需的管道,如:
import {{ your_pipe_name }} from '../your/pipe/location';
将其添加到您的声明中:
TestBed.configureTestingModule({ declarations: [ your_pipe ] });
快乐编码!
看起来你给你的管道起了别名/命名,但没有人据此回答。例如,如果您的管道已命名,myCustomPipe但这与管道的类名称不同:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myCustomPipe',
pure: false
})
export class MyPipe implements PipeTransform {
// ....
}
Run Code Online (Sandbox Code Playgroud)
然后在您的spec.ts文件中,您可以按如下方式导入管道,否则将找不到它:
import { MyPipe as myCustomPipe } from 'path/to/pipe';
Run Code Online (Sandbox Code Playgroud)
并且在beforeEach()您需要将别名引用为 adeclaration和 a provider:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ ... ],
declarations: [ myCustomPipe, etc],
providers: [ myCustomPipe, etc ]
}).compilecomponents();
// etc
});
Run Code Online (Sandbox Code Playgroud)
Elm*_*tas -1
你应该开始类似的事情
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();
});
});
Run Code Online (Sandbox Code Playgroud)