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?
Asked
Active
Viewed 6,115 times
2 Answers
11
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';}
});
-
With the more modern, I got this issue: Attempting to change access mechanism for an unconfigurable property. defineProperty@[native code] – Pierre Trollé Nov 13 '17 at 20:47
-
Similar error here: TypeError: Cannot redefine property: language at Function.defineProperty (
) – ffxsam Aug 03 '18 at 19:10 -
Object.define will not work in this case because `navigator` read only and that property is non-configurable, ie it's `configurable` attribute is set to false. – toads Feb 18 '21 at 18:37
4
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
});

cklam
- 156
- 5