我试图为一个接受对象作为参数的Pipe编写单元测试。此对象是从模拟服务创建的。
单元测试管道时是否可以使用模拟服务?我是否必须在测试中包含使用管道的组件?
PIPE - 此管道基本上接受一个对象和一组参数。基于参数,它操纵对象参数并返回它。
@Pipe({
name: 'myPipe'
})
export class MyPipe implements PipeTransform {
transform(myData: models.MyInfo, args: string[]): string { //stuff here }
}
MOCK SERVICE - 模拟服务查询在管道参数中使用的对象数组。
@Injectable()
export class MockMyService {
getMyInfo(){
//logic
}
在组件中使用管道的示例 - 以下是如何使用它的示例
this.xObj = this.realService.GetInfo();
this.myList = this.myPipe.transform(this.xObj[0], ['a', 'b', 'c',]).split(',');
我试过的单位测试 - 我尝试了几件事。下面的代码显示了我如何尝试耦合Component和Pipe,以及尝试测试没有组件的管道。
//core dependencies
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpModule } from '@angular/http';
import { DatePipe } from '@angular/common';
//pipe, component being tested
import { MyPipe } from './path to pipe';
import { ComponentThatUsesPipe } from '../path to the component';
//models / other
import { MOCKEDOBJECT } from '..path'
//services
import { MockMyService } from '..path to service';
import { RealService } from '..path to real service';
describe('myPipe', () => {
let pipe = new MyPipe();
let component: ComponentThatUsesPipe ;
var myDetailsArray: models.ObjDetails[] = MOCKEDOBJECT ;
var myDetails: models.ObjDetails;
var myList: string[] = [];
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ComponentThatUsesPipe, MyPipe],
providers: [{provide: RealService, useClass: MockMyService}]
});
component = TestBed.createComponent(ComponentThatUsesPipe ).componentInstance;
});
this.myList = pipe.transform(this.myDetails.m[0], ['a','b',1,2,3]);
it('test1', () => {
expect(this.myList.findIndex(s => s.trim() === 'Med') > -1).toBe(true);
});
});
我的测试返回错误“无法读取m'的属性”。
编辑 - 能够根据' estus'的建议解决。以下评论
describe('myPipe', () => {
let pipe = new myPipe();
let myDetailsArray: models.ObjDetails[] = MOCKEDOBJECT;
let myDetails: models.ObjDetails = myDetailsArray[0];
let hasA: boolean = false;
let hasB: boolean = false;
let hasC: boolean = false;
let myList: string[] = [];
this.myList = pipe.transform(myDetails.member[0],[stuff here]).split(',');
this.hasA = (this.myList.findIndex(s => s.trim() === 'M') > -1);
this.hasB = (this.myList.findIndex(s => s.trim() === 'P') > -1);
this.hasC = (this.myList.findIndex(s => s.trim() === 'D') > -1);
it('test myPipe hasA', () => {
expect(this.hasA).toBe(true);
});
it('test myPipe hasB', () => {
expect(this.hasB).toBe(true);
});
it('test myPipe hasC', () => {
expect(this.hasC).toBe(false);
});
});