locale-env.ts 1.3 KB

1234567891011121314151617181920212223242526272829
  1. /**
  2. * Browser-language pin for specs that assert localized copy. A fresh
  3. * LocaleRuntime with no stored preference opens in the language `navigator`
  4. * asks for, and jsdom reports the runner's own (`en-US`) — so a spec asserting
  5. * the product's Chinese copy states the browser it assumes instead of
  6. * inheriting the machine's.
  7. */
  8. import { afterEach, beforeEach } from 'vitest'
  9. /**
  10. * Pin `navigator.languages`/`navigator.language` for every test in the
  11. * calling file (or describe block), restoring the environment's own values
  12. * afterwards. Call at suite level, like the other vitest hooks.
  13. * @param primary - most preferred BCP 47 tag; also becomes `navigator.language`.
  14. * @param rest - further tags in preference order.
  15. */
  16. export function usePinnedBrowserLanguages(primary: string, ...rest: string[]): void {
  17. beforeEach(() => {
  18. Object.defineProperty(navigator, 'languages', { value: [primary, ...rest], configurable: true })
  19. Object.defineProperty(navigator, 'language', { value: primary, configurable: true })
  20. })
  21. afterEach(() => {
  22. // Deleting the own properties uncovers the environment's own accessors
  23. // again (Navigator declares both readonly, hence the erased receiver).
  24. const own = navigator as unknown as Record<string, unknown>
  25. delete own.languages
  26. delete own.language
  27. })
  28. }