gpt4 book ai didi

unit-testing - angular 2 使用 forkJoin 测试一个组件

转载 作者:太空狗 更新时间:2023-10-29 17:14:10 24 4
gpt4 key购买 nike

我的应用程序中有一个 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)运行测试时,它工作正常。 但是 当我使用第二种方法(with Observable.forkJoin)运行测试时,它失败并出现错误:

Expected undefined not to be undefined.

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

希望你明白我的意思。

提前致谢。

最佳答案

好吧伙计们,经过一番努力,我发现需要完成 observable 才能让 forkJoin 捕获它。
所以如果你打电话
project.next(something)
这还不够。
您还需要调用:
project.complete()
让它发挥作用!

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com