我有一个使用util函数的route guard
。
这看起来像
import { Injectable } from '@angular/core';
import { CanActivateChild, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from '../../services';
import { Observable } from 'rxjs';
import objectFromHash from '../../utils/object-from-hash/object-from-hash.util';
@Injectable()
export default class AuthGuard implements CanActivateChild {
constructor(private authService: AuthService) {}
canActivateChild(route: ActivatedRouteSnapshot): Observable<boolean> {
let hasValidSession: Observable<boolean>;
const { id_token, access_token } = objectFromHash(route.fragment);
hasValidSession = this.authService.isSessionValid(id_token, access_token);
return hasValidSession;
}
}
我目前正在尝试使用Jasmine
进行测试 - 但我不确定如何模拟objectFromHash
util函数。
我想测试在执行路线保护期间调用此功能。
我的spec文件看起来像这样
import { TestBed } from '@angular/core/testing';
import AuthGuard from './auth.guard';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AuthService } from '../../services';
describe('AuthGuard', () => {
it('should pass the route hash to a util method', () => {
const { authGuard } = setup();
// I AM UNSURE WHAT TO DO HERE?
});
const setup = () => {
TestBed.configureTestingModule({
providers: [
AuthGuard,
{
provide: AuthService,
useClass: MockAuthService,
},
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();
const authGuard = TestBed.get(AuthGuard);
const authService = TestBed.get(AuthService);
const objectFromHash = TestBed.get(objectFromHash);
return { authGuard, authService };
};
});
const MOCK_TOKEN = '';
export class MockAuthService {
isSessionValid(id_token?: string, access_token?: string) {}
}
尝试访问objectFromHash
会返回错误读取
TypeError: Cannot read property 'ngInjectableDef' of undefined
答案 0 :(得分:0)
我能够通过导入util并监视它来实现这一点。
由于util是默认导出,我必须执行此操作spyOn(helper, 'default')
import { TestBed } from '@angular/core/testing';
import AuthGuard from './auth.guard';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AuthService } from '../../services';
import * as helper from '../../utils/object-from-hash/object-from-hash.util';
describe('AuthGuard', () => {
it('should pass the route hash to a util method', () => {
const { authGuard, props } = setup({});
const objectFromHashSpy = spyOn(helper, 'default').and.returnValue({
id_token: 'foo',
access_token: 'bar',
});
authGuard.canActivateChild(props);
expect(objectFromHashSpy).toHaveBeenCalled();
});
const setup = propOverrides => {
TestBed.configureTestingModule({
providers: [
AuthGuard,
{
provide: AuthService,
useClass: MockAuthService,
},
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();
const props = Object.assign({ fragment: null }, { ...propOverrides });
const authGuard = TestBed.get(AuthGuard);
const authService = TestBed.get(AuthService);
return { authGuard, props, authService };
};
});
const MOCK_ROUTE_FRAGMENT = '';
export class MockAuthService {
isSessionValid(id_token?: string, access_token?: string) {}
}