带有内置Serverservice的Angular2 +单元测试服务

时间:2018-11-21 13:22:13

标签: angular unit-testing service server

我正在尝试第一次编写单元测试。到目前为止,我已经能够为“正常” /实习生服务编写测试。现在,我坚持使用更复杂的服务:

@Injectable()
export class BaseToolsService {

vehicles: Array<Vehicle>;
tools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
noBaseTools: BehaviorSubject<Array<Tool>> = new BehaviorSubject<Array<Tool>>(undefined);
vehiclesWithBaseTools: BehaviorSubject<Array<VehicleBaseToolsModel>> = new BehaviorSubject<Array<VehicleBaseToolsModel>>(undefined);

constructor(private readonly toolService: ToolService,
            private readonly vehicleService: VehicleService,
            private readonly notificationService: NotificationService) {
    forkJoin([this.toolService.getTools('Asset,ToolType'),
        this.vehicleService.getVehicles('Asset,VehicleModel')]).subscribe(results => {
        this.tools.next(results[0]);
        this.vehicles = results[1];
        this.filterToolsAndConvertVehicles();
    });
} 

...

到目前为止,我对单元测试的设置是:

import {BaseToolsService} from './base-tools.service';
import {ToolService} from '../../../../core/services/api/tool.service';
import {VehicleService} from '../../../../core/services/api/vehicle.service';
import {NotificationService} from '../../../../core/services/intern/notification/notification.service';
import {async, getTestBed, TestBed} from '@angular/core/testing';

    describe('Service: BaseToolsService', () => {

        let service: BaseToolsService;

        beforeEach(async(() => {
            TestBed.configureTestingModule({
                providers: [
                    ToolService,
                    VehicleService,
                    NotificationService,
                    BaseToolsService
                ]
            });
            const testBed = getTestBed();
            service = testBed.get(BaseToolsService);
        }));

    ...
    // Some Tests

问题在于服务ToolServiceVehicleService试图使服务器响应。由于它们是内置在BaseToolsService中的,所以我不知道如何模拟服务器请求/后端或如何模拟所需的数据本身,以及如何防止服务伸向服务器。当我运行测试时,它当然会失败,并显示错误Failed: Http failure response for (unknown url): 0 Unknown Error

有没有一种方法可以模拟服务器响应,该响应比我要测试的服务深一层?还是问题在其他地方? (由于我是单元测试的新手,所以我怀疑自己所做的一切正确无误)

0 个答案:

没有答案