How to set the browser's language in Cypress.io (electron/chrome)?

拟墨画扇 提交于 2020-12-01 09:49:26

问题


My question is about configuring Cypress to launch a browser instance in a certain language.

In order to:

  • make assertions on localized (i18n) text labels?
  • check i18n features (switching between languages)
  • bypass issues of Continuous Integration (CI/CD) when, for example, on a local computer, the browser default to fr_FR, and on the CI/CD VM it defaults to en_US?

I tried (without much success):

  • using LANGUAGE=en_US from the terminal invocation,
  • using the Browser's API plugin (see Cypress' browser launch API documentation)

Thanks!


回答1:


from Gleb Bahmutov:

you set it during cy.visit using onBeforeLoad with something like Object.defineProperty(navigator, 'language', { value: 'de-GE' })

src: https://gitter.im/cypress-io/cypress?at=5d61408a07d1ff39f8769545




回答2:


navigator has two lang props:

  • language ({ value: 'en-GB'}
  • languages(['en-GB'])

navigator.language refers to the first element of navigator.languages but some libraries check navigator.languages[0] instead of navigator.language, so better if you set both properties

onBeforeLoad: (window, ...args) => {
  Object.defineProperty(window.navigator, 'language', { value: 'en-GB' });
  Object.defineProperty(window.navigator, 'languages', ['en-GB']);

ref: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages




回答3:


To set the language in the browser and also for request, which was what I had to do for my tests, the following worked for me:

cy.visit('url', {
    onBeforeLoad(win) {
      Object.defineProperty(win.navigator, 'language', { value: 'de-DE' });
      Object.defineProperty(win.navigator, 'languages', { value: ['de'] });
      Object.defineProperty(win.navigator, 'accept_languages', { value: ['de'] });
    },
    headers: {
      'Accept-Language': 'de',
    },
});


来源:https://stackoverflow.com/questions/56791796/how-to-set-the-browsers-language-in-cypress-io-electron-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!