由于我升级到Angular2 rc3,任何需要注入路由器的测试现在都失败了。以前我使用路由器/测试文件中提供的ROUTER_FAKE_PROVIDERS,但似乎不再存在。有什么建议?
答案 0 :(得分:2)
我使用了这个设置来初始化路由器。 https://github.com/angular/angular/blob/master/modules/%40angular/router/test/router.spec.ts
期望Angular2尽快提供它作为TestProvider。
import {Location, LocationStrategy} from '@angular/common';
import {SpyLocation} from '@angular/common/testing';
import {MockLocationStrategy} from '@angular/common/testing/mock_location_strategy';
import {Component, Injector, ComponentResolver} from '@angular/core';
import {ActivatedRoute, ActivatedRouteSnapshot, CanActivate, CanDeactivate, DefaultUrlSerializer, Event, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Params, ROUTER_DIRECTIVES, Router, RouterConfig, RouterOutletMap, RouterStateSnapshot, RoutesRecognized, UrlSerializer} from '@angular/router';
export function provideTestRouter(RootCmp:any, config: RouterConfig):any[]{
return [
RouterOutletMap,
{provide: UrlSerializer, useClass: DefaultUrlSerializer},
{provide: Location, useClass: SpyLocation},
{provide: LocationStrategy, useClass: MockLocationStrategy},
{
provide: Router,
useFactory: (resolver: ComponentResolver, urlSerializer: UrlSerializer, outletMap: RouterOutletMap, location: Location, injector: Injector) => {
return new (<any>Router)(
RootCmp, resolver, urlSerializer, outletMap, location, injector, config);
},
deps: [ComponentResolver, UrlSerializer, RouterOutletMap, Location, Injector]
},
{provide: ActivatedRoute, useFactory: (r: Router) => r.routerState.root, deps: [Router]},
];
};
答案 1 :(得分:0)
看看my answer here,您似乎遇到了类似的问题。
单元测试时,某些服务有时会因为没有在正常环境中使用而导致问题。您可以测试是否已调用它,而无需通过整个服务运行单元测试。通过创建一个模拟类来做到这一点。
根据该帖子,您可以做以下事情:
describe('foo', () => {
class MockRouter{}
beforeEachProviders(() => [
{provide: ROUTER_PROVIDERS, useClass: MockRouter}
]);
it('should foo',
async(inject([FooComponent, ROUTER_PROVIDERS], (foo: FooComponent, mockRouter: MockRouter) => {
expect(mockRouter).toHaveBeenCalled();
});
})));