如何使用 Injector 在函数中模拟注入的服务
How to mock a injected service in a function with Injector
在 Angular 7.x 我有一个全局错误处理,用 Injector 注入他的服务。所以每个函数都有一个注入器的引用,像这样:
import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { LoggingService } from '../logging/logging.service';
import { EnvironmentService } from '../services/environment.service';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(private readonly injector: Injector, private readonly zone: NgZone) {}
handleError(error: any): void {
// Handle Client Error (Angular Error, ReferenceError...)
this.processError(error);
throw error;
}
processError(error: any): void {
const environmentService = this.injector.get(EnvironmentService);
const environment = environmentService.getEnvironment();
if (!environment.production) {
console.error(error);
} else {
// Log the expection to the logger
this.logException(error);
this.zone.run(() => {
this.navigateToErrorPage(error);
});
}
}
private logException(error: any): void {
const loggingService = this.injector.get(LoggingService);
loggingService.logException(error);
}
private navigateToErrorPage(error: any): void {
const router = this.injector.get(Router);
router.navigate(['/500'], { queryParams: { error } });
}
}
如您所见,在 processError
函数中我注入了环境服务。此服务的唯一目标是能够在我的规范测试中模拟环境。我在另一个服务测试中这样做,但我将其与依赖注入一起使用,而不是与 this.injector.get(...)
函数一起使用。
有人知道我是怎么嘲笑这个的吗?
it('should log the error if the environment is in production', () => {
// Arrange
const environmentSpy = jasmine.createSpyObj('EnvironmentService', 'getEnvironment'); ??? How do I mock this ???
const error: Error = new Error('New Error');
spyOn<any>(errorHandler, 'logException');
// Act
errorHandler.processError(error);
// Assert
expect(errorHandler['logException']).toHaveBeenCalledWith(error);
});
您可以监视 Injector 和 return 一个伪造的 class 代替具有自定义 getEnvironment()
方法的 EnvironmentService:
spyOn(TestBed.get(Injector), 'get').and.callFake((token) => {
if (token === EnvironmentService) {
// Return a mocked EnvironmentService class
return {
getEnvironment: () => { return { production: true }; }
};
} else {
// Otherwise, return whatever was originally defined in the TestBed
return TestBed.get(token);
}
});
或者,您可以使用真正的 Injector 并监视 EnvironmentService:
spyOn(TestBed.get(EnvironmentService), 'getEnvironment').and
.returnValue({ production: true });
在 Angular 7.x 我有一个全局错误处理,用 Injector 注入他的服务。所以每个函数都有一个注入器的引用,像这样:
import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { LoggingService } from '../logging/logging.service';
import { EnvironmentService } from '../services/environment.service';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(private readonly injector: Injector, private readonly zone: NgZone) {}
handleError(error: any): void {
// Handle Client Error (Angular Error, ReferenceError...)
this.processError(error);
throw error;
}
processError(error: any): void {
const environmentService = this.injector.get(EnvironmentService);
const environment = environmentService.getEnvironment();
if (!environment.production) {
console.error(error);
} else {
// Log the expection to the logger
this.logException(error);
this.zone.run(() => {
this.navigateToErrorPage(error);
});
}
}
private logException(error: any): void {
const loggingService = this.injector.get(LoggingService);
loggingService.logException(error);
}
private navigateToErrorPage(error: any): void {
const router = this.injector.get(Router);
router.navigate(['/500'], { queryParams: { error } });
}
}
如您所见,在 processError
函数中我注入了环境服务。此服务的唯一目标是能够在我的规范测试中模拟环境。我在另一个服务测试中这样做,但我将其与依赖注入一起使用,而不是与 this.injector.get(...)
函数一起使用。
有人知道我是怎么嘲笑这个的吗?
it('should log the error if the environment is in production', () => {
// Arrange
const environmentSpy = jasmine.createSpyObj('EnvironmentService', 'getEnvironment'); ??? How do I mock this ???
const error: Error = new Error('New Error');
spyOn<any>(errorHandler, 'logException');
// Act
errorHandler.processError(error);
// Assert
expect(errorHandler['logException']).toHaveBeenCalledWith(error);
});
您可以监视 Injector 和 return 一个伪造的 class 代替具有自定义 getEnvironment()
方法的 EnvironmentService:
spyOn(TestBed.get(Injector), 'get').and.callFake((token) => {
if (token === EnvironmentService) {
// Return a mocked EnvironmentService class
return {
getEnvironment: () => { return { production: true }; }
};
} else {
// Otherwise, return whatever was originally defined in the TestBed
return TestBed.get(token);
}
});
或者,您可以使用真正的 Injector 并监视 EnvironmentService:
spyOn(TestBed.get(EnvironmentService), 'getEnvironment').and
.returnValue({ production: true });