Angular 2,具有可观察性的管道测试没有变换访问权限

时间:2019-04-18 23:07:19

标签: angular unit-testing

我正在为管道编写单元测试。管道使用自定义服务来请求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;
        }
      })
    );
  }
}

0 个答案:

没有答案