我的应用程序中有一个 LogComponent 。在 ngOnInit 内部,我通过 LogService 从服务器检索日志,并将其显示在网格中。

这里有两种方法来做到这一点:

第一:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { Log } from './log';
import { LogService } from './log.service';
import * as globals from '../../globals';
import { DataTransformService, HttpHandlerService, StateManagerService } from '../../shared';

@Component({
  selector: 'app-log',
  templateUrl: 'log.component.html',
  styleUrls: ['log.component.css'],
  providers: [ DataTransformService, HttpHandlerService, LogService, StateManagerService]
})
export class LogComponent implements OnInit {

  localGlobals: any = globals;

  logs: Log[];

  currentPage: number;
  totalRecords: number = 0;
  firstRowIndex: number = 0;

  constructor(
    private stateManagerService: StateManagerService,
    private httpHandlerService: HttpHandlerService,
    private logService: LogService,
    private dataTransformService: DataTransformService,
    private router: Router
  ) {}

  ngOnInit() {

    //get page number from local storage
    this.currentPage = this.stateManagerService.getParamFromState(this.router.url, 'page');
    this.firstRowIndex = this.currentPage * this.localGlobals.ROWS_PER_PAGE - this.localGlobals.ROWS_PER_PAGE;

    //get total count
    let respHandler = (res: any) => {
      this.totalRecords = res.headers.get('X-Pagination-Total-Count');
      return this.httpHandlerService.extractData(res);
    };

    this.logService.search(this.currentPage, respHandler).subscribe(
      logs => {
        this.logs = logs;
      },
      err => console.error(err)
    );

  }

}

第一种方法使用此功能来检索日志:
this.logService.search(this.currentPage, respHandler).subscribe(
  logs => {
    this.logs = logs;
  },
  err => console.error(err)
);

检索日志的第二种方法是通过 Observable.forkJoin :
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { Log } from './log';
import { LogService } from './log.service';
import * as globals from '../../globals';
import { DataTransformService, HttpHandlerService, StateManagerService } from '../../shared';

@Component({
  selector: 'app-log',
  templateUrl: 'log.component.html',
  styleUrls: ['log.component.css'],
  providers: [ DataTransformService, HttpHandlerService, LogService, StateManagerService]
})
export class LogComponent implements OnInit {

  localGlobals: any = globals;

  logs: Log[];

  currentPage: number;
  totalRecords: number = 0;
  firstRowIndex: number = 0;

  constructor(
    private stateManagerService: StateManagerService,
    private httpHandlerService: HttpHandlerService,
    private logService: LogService,
    private dataTransformService: DataTransformService,
    private router: Router
  ) {}

  ngOnInit() {

    //get page number from local storage
    this.currentPage = this.stateManagerService.getParamFromState(this.router.url, 'page');
    this.firstRowIndex = this.currentPage * this.localGlobals.ROWS_PER_PAGE - this.localGlobals.ROWS_PER_PAGE;

    //get total count
    let respHandler = (res: any) => {
      this.totalRecords = res.headers.get('X-Pagination-Total-Count');
      return this.httpHandlerService.extractData(res);
    };

    Observable.forkJoin(
        this.logService.search(this.currentPage, respHandler)
    ).subscribe(
      data => {
        this.logs = data[0];
      },
      err => console.error(err)
    );

  }

}

第二种方法使用此功能来检索日志:
Observable.forkJoin(
        this.logService.search(this.currentPage, respHandler)
    ).subscribe(
      data => {
        this.logs = data[0];
      },
      err => console.error(err)
    );

我对此组件进行了测试,以检查在初始化之后是否初始化了属性:
import { DebugElement, NO_ERRORS_SCHEMA }    from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { ReplaySubject } from 'rxjs/Rx';

import { Log } from './log';
import { LogComponent } from './log.component';
import { LogService } from './log.service';
import { DataTransformService, HttpHandlerService, LocalStorageService, StateManagerService } from '../../shared';

let comp:    LogComponent;
let fixture: ComponentFixture<LogComponent>;
let de:      DebugElement;

describe('LogComponent', () => {

  // async compile html and css
  beforeEach(async(() => {

    let project = new ReplaySubject(1);
    let logServiceStub = {
        search: (pageNum: number, respHandler: any) => {
            let logs = [
                { id: 1, ip: '127.0.0.1', user_id: 1, notification_event_id: 1, created_at: 1 },
                { id: 2, ip: '127.0.0.2', user_id: 2, notification_event_id: 2, created_at: 2 }
            ];
            project.next(logs);
            return project;
        }
    };

    let routerStub = {
        url: 'log_url'
    };

    TestBed.configureTestingModule({
        declarations: [ LogComponent ],
        imports: [ FormsModule ],
        providers: [
            DataTransformService,
            HttpHandlerService,
            LocalStorageService,
            { provide: Router, useValue: routerStub },
            StateManagerService
        ],
        schemas: [ NO_ERRORS_SCHEMA ]
    })
    .overrideComponent(LogComponent, {
      set: {
        providers: [
          { provide: LogService, useValue: logServiceStub }
        ]
      }
    })
    .compileComponents();

  }));

  // synchronous
  beforeEach(() => {

    fixture = TestBed.createComponent(LogComponent);

    // LogComponent test instance
    comp = fixture.componentInstance;

    de = fixture.debugElement;

  });

  it('initial variables are set after init', () => {

      fixture.detectChanges();

      console.log(comp.logs);

      //TODO: test not working when requests are in forkJoin
      expect(comp.currentPage).toBe(1);
      expect(comp.firstRowIndex).toBe(0);
      expect(comp.logs).not.toBeUndefined();
      expect(comp.logs.length).toBe(2);

  });

});

问题:当我使用第一种方法(没有Observable.forkJoin 的)运行测试时,它可以正常工作。 但当我使用第二种方法运行测试(和Observable.forkJoin )时,它失败,并显示以下错误:

预期的undefined不会是undefined。

因此,在fixture.detectChanges()之后不会初始化日志。似乎如果请求在Observable.forkJoin()内部,则初始化不会运行。我知道Observable.forkJoin()中只有1个请求,我可以采用第一种方法,但是系统中我有其他组件使用多个请求,因此需要解决此问题。

希望你明白我的意思。

提前致谢。

最佳答案

好的,经过一番苦苦挣扎,我发现forkJoin必须完成可观察的过程才能捕获它。
所以如果你打电话project.next(something)这不够。
您还需要致电:project.complete()使它起作用!

请记住,您始终可以使用zip而不是forkJoin来处理.next传播以及.complete

关于unit-testing - angular 2使用forkJoin测试组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39795523/

10-11 12:55