dataConfiguration.js
var userData = {
URIs: {
APIURI: "C"
},
EncryptedToken: "D"
};
configSetup.js
config.set({
basePath: '',
files:['dataConfiguration.js' ],
.....
UserComponentDetails:
.....some imports
import { UserDetailsService } from '../user-details.service';
declare var userData: any;
@Component({
.....more code
userFilter() {
return userData.URIs.APIURI;
}
}
Testing:
describe('UserComponentDetails', () => {
let subject:any;
let fixture: ComponentFixture<UserComponentDetails>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ UserComponentDetails ],
providers: [{ provide: UserDetailsService, useClass:
UserDetailsServiceStub }],
});
fixture = TestBed.createComponent(UserComponentDetails);
subject = fixture.componentInstance;
});
it('should return Z', () => {
subject.userData = {
URIs: {
APIURI: "Z"
},
EncryptedToken: "W"
};
let result = subject.userFilter();
expect(result).toBe("Z");
});
});
Result:
ReferenceError: userData is not defined
To resolve this issue, a method has been implemented inside the component to retrieve the userData global variable.
getUserData():any{
return userData;
}
Additionally, mocking this method in the test suite:
let n = {
URIs: {
APIURI: "mockedValueAPIURI",
},
EncryptedToken: "mockedEncryptedToken",
};
let spy = spyOn(subject, 'getUserData').and.returnValue(n);
Is there a way to mock global variables like this without needing to wrap them in methods and then mock the method instead of the variable? The goal is to keep the original application code intact if written by someone else.