当测试需要 Router
的实例时,仅提供 Router
本身是不够的:
import {Router} from '@angular/router';
import {it, inject, beforeEachProviders} from '@angular/core/testing';
import {ComponentToTest} from './component.to.test';
describe('ComponentToTest', () => {
beforeEachProviders(() => [
Router,
ComponentToTest
]);
it('should call getData() on contruct', inject([Router], (router) => {
spyOn(ComponentToTest.prototype, 'getData');
expect(ComponentToTest.prototype.getData).not.toHaveBeenCalled();
let component = new ComponentToTest(router);
expect(ComponentToTest.prototype.getData).toHaveBeenCalled();
}));
});
会出现以下错误:
但是我真的不知道如何解决路由器。
Router
参数_rootComponent:对象,
_rootComponentType:类型,
在 alpha 中,我们有
RootRouter
:import {RootRouter} from 'angular2/src/router/router';
。现在已经没有任何替代品了。_componentResolver:组件解析器,
_urlSerializer:RouterUrlSerializer,
没有关于如何提供这些的线索。
_routerOutletMap: RouterOutletMap,
似乎路由器本身已经提供了这个
_location:位置
此参数可能仍由
SpyLocation
提供:import {SpyLocation} from '@angular/common/testing';
describe('ComponentToTest', () => {
beforeEachProviders(() => [
provide(Location, { useClass: SpyLocation }),
]);
});
最佳答案
导入@angular/router/testing
并在ROUTER_FAKE_PROVIDERS
中提供beforeEachProviders()
beforeEachProviders(() => [
ROUTER_FAKE_PROVIDERS,
ComponentToTest
]);
关于 Angular 2.0.0-rc.1 + 业力 : provide Router,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37089648/