在过去一个月左右的时间里,我一直在学习Angular 2单元测试,并且遇到了一个繁琐的过程,我正试图弄清楚如何绕过。这个繁琐的过程与导入组件用于单元测试的每个提供程序有关。我想知道是否有一种方法可以导入包含我的应用程序的所有组件和提供程序的单个文件(可能是app.module.ts文件),然后我可以选择我需要的组件和提供程序。
作为参考,这是我目前在Angular单元测试中所做的事情:
// Angular and Ionic Dependencies
import { async, TestBed, tick, fakeAsync } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { SimpleChange } from '@angular/core';
import { IonicModule, Platform, NavController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { Observable } from 'rxjs/Rx';
import {
BaseRequestOptions, ConnectionBackend, RequestOptions, Response,
ResponseOptions, Http, XHRBackend, HttpModule, RequestMethod
} from '@angular/http';
// My App Dependencies
import { ComponentToTest } from '/location/component-to-test';
import { ComponentProviderOne } from '/location/component-provider-one';
import { ComponentProviderTwo } from '/locaiton/component-provider-two';
import { ComponentProviderThree } from '/location/component-provider-three';
describe('ComponentToTest', () => {
let fixture;
let component;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ComponentToTest], // declare the test component
imports: [
IonicModule.forRoot(ComponentToTest)
],
providers: [
ComponentProviderOne,
ComponentProviderTwo,
ComponentProviderThree,
{ provide: XHRBackend, useClass: MockBackend},
MockBackend,
BaseRequestOptions,
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory:
(backend: XHRBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
}
}
]
});
});
}
我希望避免为所有ComponentProviderX使用所有这些导入。
我想添加的另一个参考是,在AngularJS中,我能够通过以下方式加载我的所有应用程序组件和服务:
describe('componentToTest', function() {
var $httpBackend,
$q,
$rootScope,
componentToTest,
componentServiceOne,
componentServiceTwo,
componentServiceThree;
// Load the Angular 1 module file that has
// a reference of all the apps Components and Services
beforeEach(module('angular1ModuleFile'));
beforeEach(inject(function(
_$httpBackend_,
_$q_,
_$rootScope_,
_componentToTest_,
_componentServiceOne_,
_componentServiceTwo_,
_componentServiceThree_
) {
$httpBackend = _$httpBackend_;
$q = _$q_;
$rootScope = _$rootScope_;
componentToTest = _componentToTest_;
componentServiceOne = _componentServiceOne_;
componentServiceTwo = _componentServiceTwo_;
componentServiceThree = _componentServiceThree_;
}));
});
总之,是否有可能在Angular单元测试中做类似的事情?那么,我可以使用单个导入(例如angular1ModuleFile)来加载我的Angular单元测试的所有应用程序组件和提供程序吗?