i18n.spec.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { defineComponent, nextTick } from 'vue'
  3. import { renderComponent } from '#tests/support/components/index.ts'
  4. import { i18n } from '#shared/i18n.ts'
  5. const Example = defineComponent({
  6. name: 'Example',
  7. props: {
  8. text: {
  9. type: String,
  10. required: true,
  11. },
  12. },
  13. data: () => ({ i18n }),
  14. template: '<div>{{ i18n.t(text) }}</div>',
  15. })
  16. const populateTranslationMap = () => {
  17. const map = new Map([
  18. ['yes', 'ja'],
  19. ['Hello world!', 'Hallo Welt!'],
  20. ['The second component.', 'Die zweite Komponente.'],
  21. [
  22. 'String with 3 placeholders: %s %s %s',
  23. 'Zeichenkette mit 3 Platzhaltern: %s %s %s',
  24. ],
  25. ['FORMAT_DATE', 'dd/mm/yyyy'],
  26. ['FORMAT_DATETIME', 'dd/mm/yyyy HH:MM:SS'],
  27. ])
  28. i18n.setTranslationMap(map)
  29. }
  30. describe('i18n', () => {
  31. afterEach(() => {
  32. i18n.setTranslationMap(new Map())
  33. })
  34. describe('in empty state', () => {
  35. it('translates to source value', () => {
  36. expect(i18n.t('unknown string')).toBe('unknown string')
  37. expect(i18n.t('yes')).toBe('yes')
  38. })
  39. })
  40. describe('with translation data', () => {
  41. beforeEach(() => {
  42. populateTranslationMap()
  43. })
  44. it('translates known strings', () => {
  45. expect(i18n.t('yes')).toBe('ja')
  46. })
  47. it('handles placeholders correctly', () => {
  48. expect(i18n.t('String with 3 placeholders: %s %s %s', 1, 2)).toBe(
  49. 'Zeichenkette mit 3 Platzhaltern: 1 2 %s',
  50. )
  51. })
  52. it('translates dates', () => {
  53. expect(i18n.date('2021-04-09T10:11:12Z')).toBe('09/04/2021')
  54. expect(i18n.dateTime('2021-04-09T10:11:12Z')).toBe('09/04/2021 10:11:12')
  55. expect(i18n.relativeDateTime(new Date().toISOString())).toBe('just now')
  56. expect(i18n.dateTimeISO('2021-04-09T10:11:12Z')).toBe(
  57. '2021-04-09T10:11:12.000Z',
  58. )
  59. })
  60. it('returns date/time format information', () => {
  61. expect(i18n.getTimeFormatType()).toBe('24hour')
  62. expect(i18n.getDateFormat()).toBe('dd/mm/yyyy')
  63. expect(i18n.getDateTimeFormat()).toBe('dd/mm/yyyy HH:MM:SS')
  64. })
  65. it('updates (reactive) translations automatically', async () => {
  66. const { container } = renderComponent(Example, {
  67. props: {
  68. text: 'Hello world!',
  69. },
  70. global: {
  71. mocks: {
  72. i18n,
  73. },
  74. },
  75. })
  76. expect(container).toHaveTextContent('Hallo Welt!')
  77. i18n.setTranslationMap(new Map())
  78. await nextTick()
  79. expect(container).toHaveTextContent('Hello world!')
  80. })
  81. })
  82. })