【问题标题】:angular unit test function.pipe is not a function角度单元测试函数。管道不是函数
【发布时间】:2019-11-20 17:19:09
【问题描述】:

我知道有一个类似的问题here

但我正在按照建议的答案进行操作,但我仍然收到此错误

基本上我有这样的功能

checkForInvitation() {
        this._join.joinInformationSource.pipe(filter(x => x !== null)).subscribe(result => {
            this.joinInformation = result;
            this.setFields(result.userInfo);
        });
    }

基本上它获取信息,然后调用另一个方法来预填充一些表单字段。

现在我正在尝试测试这种方法,所以我创建了一个像这样的间谍......

// ...

const joinServiceSpy = jasmine.createSpyObj('JoinService', ['joinInformationSource']);

// ...

providers: [
    { provide: JoinService, useValue: joinServiceSpy }
]

// ...

joinService = TestBed.get(JoinService);

it('should prepopulate fields if there is join information', () => {
   let joinInfoSpy = joinService.joinInformationSource.and.returnValue(
       of(
          // ... object
       )
   )
});

现在当我运行 ng test 时,我反复收到此错误

this._join.joinInformationSource.pipe is not a function

这是我的加入服务

joinInformationSource = new BehaviorSubject<JoinInformation>(null);

setJoinInformation(joinInformation: JoinInformation) {
    this.joinInformationSource.next(joinInformation);
}

我在这里做错了什么??

【问题讨论】:

  • 你能复制这个吗?
  • 什么时候调用 checkForInvitation()?在构造函数/onInit 内部还是仅在模板交互上?

标签: angular


【解决方案1】:

根据文档createSpyObj 接受方法列表作为第二个参数。因此,当您创建模拟对象时,您将 joinInformationSource 创建为一个函数。

const joinServiceSpy = jasmine.createSpyObj('JoinService', ['joinInformationSource']);

//now joinSeverSpy contains method joinInformationSource

但在您的代码中,您使用 joinInformationSource 作为字段

// _join.joinInformationSource has been used as a field

this._join.joinInformationSource.pipe(filter(x => x !== null)).subscribe(result => {
    this.joinInformation = result;
    this.setFields(result.userInfo);
});

因为joinInformationSource 是一个函数,所以它肯定没有pipe 方法。解决方案很少。其中之一是使用spyOnProperty 方法:

//create a service object and define a property

const joinService: any = new Object();
Object.defineProperty(joinService, 'joinInformationSource', {get: () => {}});

//then create a spy on the property

it('should prepopulate fields if there is join information', () => {
    let joinInfoSpy = spyOnProperty(joinService, 'joinInformationSource', 'get')
        .and.returnValue(
            new BehaviorSubject<JoinInformation>(//object)
        )
    }
    //the rest of the code
);

【讨论】:

  • 那么我将如何测试这个功能??
猜你喜欢
  • 2017-01-03
  • 1970-01-01
  • 2021-11-12
  • 2022-01-22
  • 1970-01-01
  • 2017-11-19
  • 2016-08-07
  • 2021-11-17
  • 2014-12-05
相关资源
最近更新 更多