首页 > 解决方案 > 仅在运行 Angular Jasmine 测试时未定义对 observable 的订阅,但在运行应用程序本身时定义

问题描述

我为此功能编写了一个单元测试:

getCarsAndSetup(){
    this.getCars();
    this.getFactoryInfo();
}

这是 getCars() 函数:

getCars() {
     const subscription = this.carDetailsService.getAll().subscribe((carDetails) => {
     this.carInfoService.setCars(carDetails);
     subscription.unsubscribe();  <-------------- Here the 
                                               subscription is undefined
                                                when running the test, 
                                                however when running
                                               the app, the subscription 
                                                is defined and
                                                  everything is fine
    });
}

这是单元测试:

fdescribe('getCarsAndSetup', () => {
    it('should get cars and set them up', () => {
        component.getFactoriesAndUnsubscribe();
        spyOn(component, "getCars");
        spyOn(component, "getFactoryInfo");
        expect(component.getCars).toHaveBeenCalled();
        expect(component.getFactoryInfo).toHaveBeenCalled();
    });
  });

我正在为 carDetailsS​​ervice 使用模拟。这是 carDetailsS​​ervice 模拟中的 getAll() 方法:

getAll(): Observable<CarModel[]> {
    return Observable.create((observer:any) => {
        observer.next([]);
    });
}

这与 REAL carDetailsS​​ervice 中的方法相同:

getAll(): Observable<CarModel[]> {
    return this.http.get<CarModel[]>(this.carUrl);
}

问题是,当我运行应用程序本身时,定义了 getCars() 方法中的订阅,我可以取消订阅等等,一切都很好。

但是,当我运行测试时,此测试失败,因为由于某种原因,当我尝试取消订阅时,getCars() 函数中未定义订阅。

仅在运行测试时未定义订阅的原因可能是什么?这可能与我嘲笑 carDetailsS​​ervice 的 getAll() 函数的方式有关吗?

标签: angularunit-testingjasminerxjskarma-jasmine

解决方案


这里的问题是您依赖源 Observable 的同步/异步行为。

在您的真实应用程序中,您this.carDetailsService.getAll()是一个真正的远程调用(异步),因此它的订阅被分配给subscription并且一切正常。但是,在您的测试中,可能会模拟相同的调用,因此是同步的,因此在您要调用subscription.unsubscribe()它时仍然是undefined(该subscribe方法仍在执行并且尚未返回任何订阅)。

您可以做的最简单的事情是传递一个箭头函数来subscribe使用function关键字。RxJS 将this订阅者处理程序内部绑定到其内部订阅对象(我知道这是一个有点棘手的方法,但它打算以这种方式使用)。

const that = this;
this.carDetailsService.getAll().subscribe(function(carDetails) { // note the `function` keyword
  that.carInfoService.setCars(carDetails);
  this.unsubscribe();
});

另一种方法可能是使用takeUntilSubject 并在您的subscribe.

这种行为将来可能会改变:https ://github.com/ReactiveX/rxjs/issues/3983

不同用例中的相同问题:RxJs: Calculating observable array length in component


推荐阅读