简体   繁体   中英

Testing navigator.browserLanguage or navigator.language with Sinon.js

How to use sandbox.stub of Testing framework Sinon to overwrite eg navigator.language or navigator.userAgent for testing?

When I try to use the following:

suite('agent', function () {
  var sandbox;
  setup(function () {
    // create sandbox environment for mocking about
    sandbox = sinon.sandbox.create();
  });
  teardown(function () {
    // restore the environment as it was before
    sandbox.restore();
  });
  test('language', function () {
    assert.equal(au.env.agent.language, navigator.language);
    if (!navigator.language) assert.equal(au.env.agent.language, 'de');
    var lang = "test_URK";
    sandbox.stub(window.navigator, 'language', lang);
    assert.equal(au.env.agent.language, lang);
  });
});

then I'll get the following error: Cannot stub non-existent own property language :

Non of these stubs work as expected:

  • sandbox.stub(window.navigator, 'language', lang);
  • sandbox.stub(navigator, 'browserLanguage', lang);

are mocking the navigator object .

Any hints?

As described in Mocking a useragent in javascript? , you can:

  navigator.__defineGetter__('language', function(){
      return 'foo';
  });

Or the more modern:

  Object.defineProperty(navigator, 'language', { get: function() {return 'bar';} }); 

No need for Sinon here. The problem is, at least Chrome + Safari prevent changes to navigator.language (and others), as they are read-only. But you can just recreate the whole navigator object, as you anyway mocking it out.

navigator = {
    userLanguage: 'de',
    language: 'en'
};

In my tests, I would then just define the desired language before calling my functions.

// eg: following fn returns navigator.userLanguage || navigator.language;
navigator.userLanguage = undefined; // non IE
LanguageRedirection.getBrowserLanguage().then(function(lang){
   expect(res).toEqual('en');
});

This worked for me:

sinon.stub(global, "navigator").returns({
  userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM