问题描述
我正在尝试为具有'AuthenticationService'依赖性的警卫编写单元测试。我想模拟该服务的身份验证方法。该服务由我编写的角度库导出。 但是,我似乎无法通过玩笑来嘲笑它!
首先,测试规格:
import { AuthenticationService } from '@XXX/XXX-common'; // Importing the service.
import { AGuard } from './a.guard';
describe('AGuard',() => {
let guard: AGuard;
let fakeRouter = {navigate: jest.fn()}
let fakeAuthenticationService = {authenticate: jest.fn()} // Mocking.
// Provide the mocked dependency to the guard.
beforeEach(() => {
Testbed.configureTestingModule({
providers: [
{provide: AuthenticationService,useValue: fakeAuthenticationService},{provide: Router,useValue: fakeRouter}
]});
guard = Testbed.inject(AGuard);
});
it('should be created',() => {
expect(guard).toBeTruthy();
});
});
运行测试后...
实际错误之前的完整堆栈跟踪:
at Object.<anonymous> (../../XXX-common/src/lib/core/services/config/environment.service.ts:8:42)
at Object.<anonymous> (../../XXX-common/src/lib/authentication/XXX-security.module.ts:3:1)
at Object.<anonymous> (../../XXX-common/src/lib/authentication/export.ts:2:1)
at Object.<anonymous> (../../XXX-common/src/index.ts:2:1)
我的身份验证模块的export.ts:
// Error already takes place here!
export * from './authentication.module';
// [...]
// [...]
// [...]
// The actual service I need mocked
export * from './services/authentication.service';
我的身份验证模块中的导入:
import { EnvironmentConfig,EnvironmentService } from '../core/services/config/environment.service';
实际错误:
ReferenceError: Cannot access 'EnvironmentConfig' before initialization
6 | export class EnvironmentService {
7 |
> 8 | constructor(private environmentConfig: EnvironmentConfig) { }
| ^
9 |
10 | public get EnvironmentConfig() {
11 | return this.environmentConfig;
它之所以会这样,是因为我正在使用所有导出成员的实际实现来导入整个模块。然后只是嘲笑我需要的东西,有点像间谍。有没有办法完全模拟要导入服务的模块?我认为这可以解决我的问题。而且我真的不需要此模块的任何其他功能。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)