Мне было интересно, может ли кто-нибудь помочь мне в этой теме, я пишу некоторые модульные тесты, касающиеся некоторых функциональных возможностей, которые выполняются в зависимости от среды, которая работает в данный момент.
Это мой исходный код компонента, который я хочу создать для модульного теста:
import { Component, OnInit } from '@angular/core';
// DEV environment
import { environment } from '@env/environment';
// PROD environment
// import { environment } from '@env/environment.prod';
import { Logger } from '@app/core/logger/logger.service';
import { I18nService } from '@app/core/language/i18n.service';
let log: Logger;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [I18nService]
})
export class AppComponent implements OnInit {
constructor(private i18nService: I18nService) {
log = new Logger('X');
}
ngOnInit() {
// Setup logger
if (environment.isProduction) {
Logger.enableProductionMode();
}
log.debug('init');
// Setup translations
this.i18nService.init(environment.defaultLanguage, environment.supportedLanguages);
}
И это модульное тестирование:
import * as environmentDEV from '@env/environment';
import * as environmentPRO from '@env/environment.prod';
...
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
// Spies declarations
let spy_initI8nServiceMethod: jasmine.Spy;
let spy_debugLoggerAttr: jasmine.Spy;
let spy_enableProductionModeLoggerMethod: jasmine.Spy;
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot()],
declarations: [AppComponent],
providers: [I18nService]
});
TestBed.compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.debugElement.componentInstance;
}));
beforeEach(inject([I18nService],
(_i18nService: I18nService) => {
i18nService = _i18nService;
// Create spies
// Spies
spy_initI8nServiceMethod = spyOn(I18nService.prototype, 'init');
spy_debugLoggerAttr = spyOn(Logger.prototype, 'debug');
spy_enableProductionModeLoggerMethod = spyOn(Logger, 'enableProductionMode');
}));
it('should component init on PRO environment',
async(() => {
spyOn(environment, 'isProduction').and.returnValue(environmentPRO.environment.isProduction);
spyOn(environment, 'defaultLanguage').and.returnValue(environmentPRO.environment.defaultLanguage);
spyOn(environment, 'supportedLanguages').and.returnValue(environmentPRO.environment.supportedLanguages);
component.ngOnInit();
expect(spy_enableProductionModeLoggerMethod).toHaveBeenCalledBefore(spy_debugLoggerAttr);
expect(spy_debugLoggerAttr).toHaveBeenCalledBefore(spy_initI8nServiceMethod);
expect(spy_initI8nServiceMethod).toHaveBeenCalledWith(environmentPRO.environment.defaultLanguage,
environmentPRO.environment.supportedLanguages);
}));
});
Моя проблемав том, что я не могу заставить постоянную среду возвращать определенные значения, я пробовал оба spyOn и spyOnAttribute с одинаковым результатом.Что здесь не так?мне попробовать другой подход?