由于我升级到 Angular2 rc3,任何需要注入路由器的测试现在都失败了。以前我使用的是路由器/测试文件中提供的 ROUTER_FAKE_PROVIDERS,但它似乎不再存在。有什么建议么?
问问题
654 次
2 回答
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]},
];
};
于 2016-07-01T14:42:38.420 回答
0
看看我的回答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();
});
})));
于 2016-06-29T18:02:21.390 回答