I am using Jasmine for testing JavaScript code and I was wondering if there is a way to set navigator language (or the browser language) for specific tests?
As described in Mocking a useragent in javascript?, you can:
navigator.__defineGetter__('language', function(){
return 'foo';
});
Or, you can use the more modern:
Object.defineProperty(navigator, 'language', {
get: function() {return 'bar';}
});
The answer from @abendigo works but it would indeed show 'Cannot redefine property' when you're trying to overrule the property twice.
In the post that he linked to they suggested to add configurable: true
, so:
Object.defineProperty(navigator, 'language', {
get: function() { return 'bar'; }, // Or just get: () => 'bar',
configurable: true
});
Btw, a getter is not a must, you can also use a value notation:
Object.defineProperty(navigator, 'language', {
value: 'bar',
configurable: true
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With