问题描述
我有一个简单的路由器保护,我正在尝试测试 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
.我可以像这样创建 ActivatedRouteSnapshot new ActivatedRouteSnapshot()
但我不知道如何创建一个模拟的 RouterStateSnapshot
.
I have a simple router guard and I am trying to test the canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot )
. I can create the ActivatedRouteSnapshot like this new ActivatedRouteSnapshot()
but I cannot figure out how to create a mocked RouterStateSnapshot
.
根据我尝试过的代码...
Per the code I tried...
let createEmptyStateSnapshot = function(
urlTree: UrlTree, rootComponent: Type<any>){
const emptyParams = {};
const emptyData = {};
const emptyQueryParams = {};
const fragment = '';
const activated = new ActivatedRouteSnapshot();
const state = new RouterStateSnapshot(new TreeNode<ActivatedRouteSnapshot>(activated, []));
return {
state: state,
activated: activated
}
}
但是 import {TreeNode} from "@angular/router/src/utils/tree";
似乎需要转译之类的,因为我得到...
But import {TreeNode} from "@angular/router/src/utils/tree";
seems to need to be transpiled or something because I get...
未捕获的语法错误:意外的令牌导出在 webpack:///~/@angular/router/src/utils/tree.js:8:0 <- test.bundle.ts:72431
推荐答案
我设法做的略有不同,但它应该适合你:
I managed to do it slightly differently but it should work for you :
...
let mockSnapshot:any = jasmine.createSpyObj<RouterStateSnapshot>("RouterStateSnapshot", ['toString']);
@Component({
template: '<router-outlet></router-outlet>'
})
class RoutingComponent { }
@Component({
template: ''
})
class DummyComponent { }
describe('Testing guard', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([
{path: 'route1', component: DummyComponent},
{path: 'route2', component: DummyComponent},
...
])
],
declarations: [DummyComponent, RoutingComponent],
providers: [
GuardClass,
{provide: RouterStateSnapshot, useValue: mockSnapshot}
]
}).compileComponents());
it('should not allow user to overcome the guard for whatever reasons',
inject([GuardClass], (guard:GuardClass) => {
let fixture = TestBed.createComponent(RoutingComponent);
expect(guard.canActivate(new ActivatedRouteSnapshot(), mockSnapshot)).toBe(false);
})
...
这篇关于如何为 Router Guard Jasmine 测试模拟 RouterStateSnapshot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!