DEV Community

Cover image for Working with date locale in your Cypress test
sesay
sesay

Posted on

Working with date locale in your Cypress test

I recently came across a challenge when working with date locale's especially within the browser, and sometimes it could be very challenging there is a quick way around this using the Intl.DateTimeFormat() more info

But using the resolvedOptions() in the DateTimeFormat prototype method gives us more information and the browser locale is one of them.

Using Cypress

I was tempted to actually run this cypress code, but the problem is this won't work unless its inside a test, for example an "it" block or in a Gherkin syntax if you using cucumber.

const dateLocale = () => {
  let locale = '';
  cy.window().then(win => {
    locale = win.navigator.language;
  });

  return locale;
}

My Solution

For me i prefer using the Intl.DateTimeFormat().resolvedOptions() constructor object as this offer me flexibility and less code as i can easily extract the locale. An example code will look like this

const { locale: dateLocale } = new Intl.DateTimeFormat().resolvedOptions(); console.log(dateLocale); // logs the resolvedOptions() props const date = Intl.DateTimeFormat(dateLocale).format(new Date()); console.log(date); // browser default locale date

Final Words

This is solely my opinion please feel free to drop your comment's in which approach do you think makes sense and how will you solve a problem like this.

If you enjoyed the article, consider sharing it so more people can benefit from it! Also, feel free to follow me on Twitter @don_csay with your opinions.

Top comments (0)