mockData.js
var userInfo = {
URLs: {
AppURL: "A"
},
EncryptedBPC: "B"
};
karma.config.js
config.set({
basePath: '',
files:['mockData.js' ],
.....
ComponentDetailsComponent
.....some imports
import { ComponentDetailsService } from '../component-details.service';
declare var userInfo: any;
@Component({
.....more code
rfxFilter() {
return userInfo.URLs.AppURL;
}
}
Spec:
describe('ComponentDetailsComponent', () => {
let subject:any;
let fixture: ComponentFixture<ComponentDetailsComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ ComponentDetailsComponent ],
providers: [{ provide: ComponentDetailsService, useClass:
ComponentDetailsServiceStub }],
});
fixture = TestBed.createComponent(ComponentDetailsComponent);
subject = fixture.componentInstance;
});
it('should return X', () => {
subject.userInfo = {
URLs: {
AppURL: "X"
},
EncryptedBPC: "Y"
};
let result = subject.rfxFilter();
expect(result).toBe("X");
});
});
Выход:
ReferenceError: userInfo не определено
Я заставил его работать, создав метод внутри компонента, который будет возвращать глобальную переменную userInfo.
getuserInfo():any{
return userInfo;
}
И издевается над этим методом в спецификации:
let m = {
URLs: {
AppURL: "mockvalueAppURL",
},
EncryptedBPC: "mockEncryptedBPC",
};
let spy = spyOn(subject, 'getuserInfo').and.returnValue(m);
Разве невозможно смоделировать такие глобальные переменные без необходимости инкапсулировать их в методы, а затем высмеивать метод вместо переменной? Я хотел бы оставить код приложения без изменений, когда он был написан кем-то другим.