我想为我的解析器编写单元测试,需要在其构造函数中使用ActivatedRouteSnapshot
,如下所示:
export class MyResolver {
constructor () {
// ...
}
resolve (private route: ActivatedRouteSnapshot) {
callFoo(route.params.val);
}
};
但是在我的单元测试中,用模拟数据提供激活路由快照的最佳方法是什么?当我尝试使用我需要的属性创建一个对象时,我收到一个错误,它无法转换为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;
}));
错误:
Type '{ params: { val: string; }; }' cannot be converted to type 'ActivatedRouteSnapshot'.
如何提供模拟的ActivatedRouteSnapshot以传递给我的解析器?
答案 0 :(得分:0)
我不确定这是否是最漂亮的解决方案,但您可以像这样嘲笑这条路线:
let route = createSpyObj('Route', ['']);
route.params = {
val: '1234'
}
答案 1 :(得分:0)
您必须提供这样的活动路线:
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);
}));
});
查看更复杂的示例here。
答案 2 :(得分:0)
如果目的只是将模拟传递给解析器,则不必使用createSpyObj
,如其他答案中所建议。另外,最好在解决方案中添加类型安全性:
const mock = <T, P extends keyof T>(obj: Pick<T, P>): T => obj as T;
it('should call foo', () => {
const route = mock<ActivatedRouteSnapshot, 'params'>({
params: {
val: '1234'
}
});
const resolver = createTheResolver();
const resolverParams = resolver.resolve(route);
...
});
答案 3 :(得分:0)
就我而言,这是最简单的事情(这也允许我写入通常为只读的“父”属性:
const route = Object.assign({}, ActivatedRouteSnapshot.prototype, {
params: {
myParam: 'some_value'
},
parent: {
params: {
myParentParam: 'some_other_value'
}
}
});
然后你只需像这样用“路由”调用你的解析器:
it('should do something with my activated route params', (done) => {
const route = Object.assign({}, ActivatedRouteSnapshot.prototype, {
params: {
myParam: 'some_value'
},
parent: {
params: {
myParentParam: 'some_other_value'
}
}
});
service.resolve(route).subscribe(res => {
expect( ... )
done();
});
});
答案 4 :(得分:0)
请注意,如果您愿意,您也可以简单地将对象转换为 ActivatedRouteSnapshot:
const mockRoute = {paramMap: convertToParamMap({'id': '123'})} as
ActivatedRouteSnapshot;
resolver.resolve(mockRoute);