【问题标题】:this.mobilityService.currentMessage.subscribe is not a function in angular unit testingthis.mobilityService.currentMessage.subscribe 不是角度单元测试中的函数
【发布时间】:2020-02-25 11:23:24
【问题描述】:

在业力单元测试中,我得到 this.mobilityService.currentMessage.subscribe is not a function 错误

下面是我试图通过服务从另一个组件获取值的 .ts 文件

  constructor(private projectService: ProjectService, private teamService: TeamserviceService) {this.getData()}

getData(){
this.projectService.currentMessage.subscribe(data => {
  if(data!=null)
  {
    this.serviceName=data.service_object.serviceName;
    this.serviceId = data.service_object.id})

这就是我的服务代码的样子 -

messageSource = new BehaviorSubject(null);
currentMessage = this.messageSource.asObservable();
getProjectList(messageSource: string[]) {
this.messageSource.next(messageSource);
}
 constructor(private http:HttpClient) {
 getAllProjectService(teamid,serviceid){
 return this.http.get(environment.TEST_AUTOMATION_ENDPOINT+'/api/projects-by-team-and-servicestore? 
teamId='+teamid+'&serviceStoreId='+serviceid+'&access_token='+this.decaccesstoken);
 }
 }

我的 .spec 文件我正在创建一个像这样的间谍对象 -

  const mockProjectService= jasmine.createSpyObj('projectService', ['getAllProjectService','currentMessage']);

由于 'currentMessage' 不是服务内的方法,我收到此错误。知道如何订阅服务内的变量吗?

【问题讨论】:

    标签: angular unit-testing jasmine observable karma-runner


    【解决方案1】:

    将您的服务代码更改为:

    messageSource = new BehaviorSubject(null);
    
    currentMessage() {
        return this.messageSource.asObservable();
    }
    getProjectList(messageSource: string[]) {
          this.messageSource.next(messageSource);
    }
     constructor(private http:HttpClient) {
     getAllProjectService(teamid,serviceid){
           return this.http.get(environment.TEST_AUTOMATION_ENDPOINT+'/api/projects-by-team- 
           and-servicestore?teamId='+teamid+'&serviceStoreId='+serviceid+'&access_token='+this.decaccesstoken);
     }
     }
    

    【讨论】:

    • 您好,感谢您的回复,但我仍然收到 TypeError: Cannot read property 'subscribe' of undefined error
    • 在getData()方法中this.projectService.currentMessage()是方法
    • 好的,因为我没有在 .spec 文件中写入返回值,所以它会抛出错误。感谢您的回答。
    猜你喜欢
    • 2017-01-03
    • 2019-11-20
    • 2021-11-12
    • 2016-08-07
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多