A. *_*uff 14 unit-testing angular angular-router
我想为我的解析器编写一个单元测试,需要ActivatedRouteSnapshot
像下面那样接受它的构造函数:
export class MyResolver {
constructor () {
// ...
}
resolve (private route: ActivatedRouteSnapshot) {
callFoo(route.params.val);
}
};
Run Code Online (Sandbox Code Playgroud)
但在我的单元测试中,用模拟数据提供激活路由快照的最佳方法是什么?当我尝试使用我需要的属性创建一个对象时,我收到一个错误,它无法转换为ActivatedRouteSnapshot:
it('should call foo', inject([MyResolver], async (myResolver: MyResolver) => {
const mockRoute = {
params: {
val: '1234'
};
};
sinon.spy(callFoo);
myResolver.resolve(mockRoute); // This is the line that errors
expect(callFoo.calledWith('1234')).to.be.true;
}));
Run Code Online (Sandbox Code Playgroud)
错误:
Type '{ params: { val: string; }; }' cannot be converted to type 'ActivatedRouteSnapshot'.
Run Code Online (Sandbox Code Playgroud)
如何提供模拟ActivatedRouteSnapshot传递给我的解析器?
您必须像这样提供活动路线:
import {TestBed} from '@angular/core/testing';
import {SomeResolver} from './some.resolver';
import {ActivatedRoute, convertToParamMap} from '@angular/router';
import {of} from 'rxjs';
describe('SomeResolver', () => {
let someResolver: SomeResolver;
let route: ActivatedRoute;
TestBed.configureTestingModule({
providers: [
{
provide: ActivatedRoute,
useValue: {snapshot: {paramMap: convertToParamMap({id: 'one-id'})}}
},
SomeResolver
]
});
beforeEach(() => {
heroResolver = TestBed.get(HeroResolver);
route = TestBed.get(ActivatedRoute);
});
it('should resolve', (() => {
someResolver.resolve(route.snapshot);
}));
});
Run Code Online (Sandbox Code Playgroud)
在此处查看更复杂的示例。
我不确定这是否是最漂亮的解决方案,但您可以像这样模拟路线:
let route = createSpyObj('Route', ['']);
route.params = {
val: '1234'
}
Run Code Online (Sandbox Code Playgroud)