首页 > 解决方案 > Jasmine 如何测试返回 httpClient observable 的函数?

问题描述

我在下面的组件中有一个函数

  getProperties(data) {
    let type = this.route.snapshot.paramMap.get('type');
    const types = {
      "easy": {
        adviceEndpoint: this.apiService.getEasy(),
      }, "medium": {
        adviceEndpoint: this.apiService.getMedium(),
      }
    }
    return types[type];
  }

apiService返回httpClient方法,例如 get、post 等。如上所示,我成功注入了所有依赖项。有趣的是,我可以选择一种类型并返回adviceEndpoint 和adviceFeatures,但它无法获取adviceEndpoint,当我打印它时它返回为未定义,如下所示安慰Object{adviceEndpoint: undefined}

   fdescribe('ExampleComponent', () => {
        let component: ExampleComponent;
        let fixture: ComponentFixture<ExampleComponent>;
        let el: DebugElement;
        let route: any;
        beforeEach(async(() => {
            const apiServiceSpy = jasmine.createSpyObj('ApiService',
                ["getEasy", "getMedium"]
            );
            TestBed.configureTestingModule({
                imports: [NgbModule, CommonModule, RouterModule.forRoot([])],
                declarations: [ExampleComponent],
                providers: [
                    { provide: ApiService, useValue: apiServiceSpy },
                    {
                        provide: ActivatedRoute,
                        useValue: {
                            snapshot: {
                                paramMap: convertToParamMap({ type: 'easy' })
                            }
                        }
                    }
                ]
            }).compileComponents().then(() => {
                fixture = TestBed.createComponent(ExampleComponent);
                route = TestBed.inject(ActivatedRoute);
                component = fixture.componentInstance;
                el = fixture.debugElement;
                fixture.detectChanges();
            });
        }));
        it("should return true properties", () => {
            const properties = component.getProperties();
            console.log(properties);
            //Object{adviceEndpoint: undefined}
        });
    });

标签: javascriptangulartypescriptjasminekarma-runner

解决方案


我希望您不要尝试在 ExampleComponent 的测试中测试您的 ApiService 模拟。如果是这样,那么只需提供一些模拟值,这样您就可以在最后检查正确的对象

it("should return true properties", () => {
  apiServiceSpy.getEasy.and.returnValue('easy-endpoint');
   const properties = component.getProperties();
   expect(properties).toEqual({adviceEndpoint: 'easy-endpoint'});
});

推荐阅读