I need to find the way to change userAgent
value. I tried to spyOn
the window.navigator.userAgent
. But that's not helping.
JS:
@Injectable()
export class DetectBrowserService {
browserIE: boolean;
constructor() {
this.browserIE = this.detectExplorer();
}
public detectExplorer() {
const brows = window.navigator.userAgent;
const msie = brows.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return true;
}
}
}
Spec:
it('should test window.navigator.userAgent', () => {
const wind = jasmine.createSpy('window.navigator.userAgent');
wind.and.returnValue('1111');
detectBrowserService = TestBed.get(DetectBrowserService);
console.log(window.navigator.userAgent);
});
I was expecting 1111
, but got the real info about my browser.
I realize this is old, but to expand on SiddAjmera's answer, here's what I did to test a safari-specific behavior. At the end of the test, it also resets the userAgent so other tests aren't affected (as Pieter De Bie requested in a comment).
I got a simple solution using Jasmine apis itself.
modify the spy in each test as per your requirement.
Not sure from which Jasmine version this API is present, but v3.4 supports this API
Once you spy any global property, it is a good practice to clear that spy
afterEach
test.Eg.
userAgent
is a read-only/constant property onwindow.navigator
. Andjasmine.createSpy
is generally used to create spies on methods and NOT properties.Now, I tried directly doing
window.navigator.userAgent = '1111';
aswindow.navigator
would simply be accessible in my tests. But I was getting an error saying:So the only option was to use the good old
__defineGetter__
. So that's what I did here:And it works:
Hope this helps!