首页 文章

如何使用rxjs 5 forkJoin测试角度5组件

提问于
浏览
0

我在我的应用程序中有一个ResultsComponent,我在同一时间通过使用rxjs forkJoin运算符连接两个服务调用 . 我想模拟rxjs运算符的数据 . 我有谷歌很多时间,尝试不同的方式,但没有找到办法做到这一点 . 谁能帮帮我吗 .

角度版本:5.2.9 rxjs版本:5.5.7 angular-cli:1.6.6

results.component.ts 中的forkJoin语句中获取此错误

TypeError:您在预期的流中提供了“未定义” . 您可以提供Observable,Promise,Array或Iterable .

results.component.ts

@Component({
  selector: "app-results",
  templateUrl: "./results.component.html",
  styleUrls: ["./results.component.scss"]
})
export class ResultsComponent 
  implements OnInit, OnDestroy {
  searchForm: FormGroup;


  constructor(
    private rxnsSearchService: RxnsSearchService,
    private rxnsSearchHitCountService: RxnsSearchHitCountService,
    public store: Store<fromAppReducer.AppState>,
    private route: ActivatedRoute,
    public formBuilder: FormBuilder,
    public router: Router
  ) {

  }

  ngOnInit() {

    this.route.queryParams.subscribe(params => {
      this.searchForm = this.formBuilder.group({
        searchInput: new FormControl(params.q, Validators.required),
        searchType: new FormControl(params.searchType),
        searchBy: new FormControl(params.searchBy)
      });
      this.store.dispatch(new AppActions.ChemQueryString(params.q));
      const rxnsObservable: Observable<Array<any>> = this.rxnsSearchService.getReactions(params, 0);
      const headCountObservable: Observable<number> = this.rxnsSearchHitCountService.getHitCount(params);
      forkJoin([rxnsObservable, headCountObservable]).subscribe(results => {
        this.reactions = results["0"];
        this.total = results["1"];
      }, (error) => {
        console.log(error);
      });
    });
    this.store.select("rxnState").subscribe(data => {
      console.log(data);
      this.searchString = data.slice(-1)[0].searchString;
    });
  }
  ngOnDestroy() {}
}

results.component.spec.ts

const dummydata = [
  {
    ruid: "02b01f46288b4f71950d03856bc8f173",
    rxnString: "Cl.NCCC1(C(F)(F)F)CC1.NCC1=CC=CC(NC"
  },
  {
    ruid: "02b01f46288b4f71950d03856bc8f173",
    rxnString: "Cl.NCCC1(C(F)(F)F)CC1.NCC1=CC=CC(NC"
  }
];
const dummyParams = {q: "[H]N(C(=O)C([H])([H])C)C1([H])CCCC22", searchType: "SUBSTRUCTURE", searchBy: "PRODUCT"};

class RouterStub {
  navigate(commands: any[], extras?: NavigationExtras) { }
}
class ActivatedRouteStub {
  private _testParams: {};
  private subject = new BehaviorSubject(this._testParams);
   queryParams = this.subject.asObservable();
  setQueryParams(params: Params) {
    this._testParams = params;
    this.subject.next(params);
  }
}

describe("ResultsComponent", () => {
  beforeEach(() => {
    activatedRoute = new ActivatedRouteStub();
  });
  let component: ResultsComponent;
  let injector;
  let store: Store<any>;
  let fixture: ComponentFixture<ResultsComponent>;
  let rxnsSearchService: RxnsSearchService;
  let rxnsSearchHitCountService: RxnsSearchHitCountService;
  let activatedRoute: ActivatedRouteStub;

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      imports: [
        ResultsModule,
        NgxPaginationModule,
        HttpClientTestingModule,
        RouterTestingModule,
        StoreModule.forRoot(fromAppReducer.reducers)
      ],
      declarations: [ ],
      providers: [
          RxnsSearchService,
          RxnsSearchHitCountService,
        { provide: ActivatedRoute, useValue: activatedRoute },
        { provide: Router, useClass: RouterStub},
        FormBuilder
      ]
    }).compileComponents();
    injector = getTestBed();
    rxnsSearchService = injector.get(RxnsSearchService);
    rxnsSearchHitCountService = injector.get(RxnsSearchHitCountService);
    spyOn(rxnsSearchService, 'getReactions').and.returnValue(Observable.of(dummydata));
    spyOn(rxnsSearchHitCountService, 'getHitCount').and.returnValue(Observable.of(300));
    store = injector.get(Store);
  }));

  beforeEach(async(() => {
    activatedRoute.setQueryParams(dummyParams);
    fixture = TestBed.createComponent(ResultsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it("should create results component", () => {
    expect(component).toBeTruthy();
  });
});

1 回答

  • 1

    我最近遇到了同样的问题并通过将forkjoin拉出到自己的方法中来解决它,然后创建一个 Spy 来返回我想要的值 .

    ngOnInit() {
    
      this.route.queryParams.subscribe(params => {
        this.searchForm = this.formBuilder.group({
          searchInput: new FormControl(params.q, Validators.required),
          searchType: new FormControl(params.searchType),
          searchBy: new FormControl(params.searchBy)
        });
        this.store.dispatch(new AppActions.ChemQueryString(params.q));
        const rxnsObservable: Observable<Array<any>> = this.rxnsSearchService.getReactions(params, 0);
        const headCountObservable: Observable<number> = this.rxnsSearchHitCountService.getHitCount(params);
    
        const data = this.getData(rxnsObservable, headCountObservable); 
        this.reactions = data["0"];
        this.total = data["1"];
      });
      this.store.select("rxnState").subscribe(data => {
        console.log(data);
        this.searchString = data.slice(-1)[0].searchString;
      });
    }
    
    getData(req1, req2) {
      forkJoin([req1, req2]).subscribe(results => {
        return results;
      }, (error) => {
        console.log(error);
      });
    }
    

    然后你的测试可能是这样的:

    spyOn(component, 'getData').and.returnValue([foo, bar]);
    

相关问题