我正在为管道编写单元测试。管道使用自定义服务来请求api数据。按照此处的概述:https://medium.com/google-developer-experts/angular-2-testing-guide-a485b6cb1ef0和我整理的其他一些资料:
describe('UserDataPipe', () => {
let pipe;
const userSvcMock = jasmine.createSpyObj('UserService', ['getUser']);
beforeEach(() => TestBed.configureTestingModule({
declarations: [UserDataPipe],
providers: [
{ provide: UserService, useValue: userSvcMock }
]
}));
beforeEach(inject([UserService], p => {
pipe = p;
}));
it('create an instance', () => {
expect(pipe).toBeTruthy();
});
it('should return user display name (firstName lastName)', () => {
console.log(pipe);
});
});
但是,pipe
无权访问我需要测试的transform
方法。它可以访问transform
方法getUser
中调用的实际可观察对象。
有人建议我使用此方法,但结果相同:
let pipe;
beforeEach(() => {
const userService = jasmine.createSpyObj('UserService', ['getUser']);
pipe = new UserDataPipe(userService);
});
管道:
@Pipe({
name: 'userData'
})
export class UserDataPipe implements PipeTransform {
constructor(private userService: UserService) {}
transform(value: string, userProp?: any): any {
let userData;
return this.userService.getUser(value).pipe(
map(res => {
userData = res;
if (!userProp) {
return userData;
} else {
const prop = userProp === 'displayName' ? `${userData.firstName} ${userData.lastName}` : res[userProp];
return prop;
}
})
);
}
}