Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock navigator language in specific tests

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?

like image 413
koninos Avatar asked Apr 12 '16 09:04

koninos


2 Answers

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';}
  });
like image 125
abendigo Avatar answered Nov 14 '22 00:11

abendigo


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
});
like image 43
cklam Avatar answered Nov 14 '22 00:11

cklam