i18n.spec.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. it('starts with empty state', () => {
  35. expect(i18n.t('unknown string')).toBe('unknown string')
  36. expect(i18n.t('yes')).toBe('yes')
  37. })
  38. describe('i18n populated', () => {
  39. beforeEach(() => {
  40. populateTranslationMap()
  41. })
  42. it('translates known strings', () => {
  43. expect(i18n.t('yes')).toBe('ja')
  44. })
  45. it('handles placeholders correctly', () => {
  46. // No arguments.
  47. expect(i18n.t('String with 3 placeholders: %s %s %s')).toBe(
  48. 'Zeichenkette mit 3 Platzhaltern: %s %s %s',
  49. )
  50. })
  51. it('translates dates', () => {
  52. expect(i18n.date('2021-04-09T10:11:12Z')).toBe('09/04/2021')
  53. expect(i18n.dateTime('2021-04-09T10:11:12Z')).toBe('09/04/2021 10:11:12')
  54. expect(i18n.relativeDateTime(new Date().toISOString())).toBe('just now')
  55. })
  56. it('updates (reactive) translations automatically', async () => {
  57. const { container } = renderComponent(Example, {
  58. props: {
  59. text: 'Hello world!',
  60. },
  61. global: {
  62. mocks: {
  63. i18n,
  64. },
  65. },
  66. })
  67. expect(container).toHaveTextContent('Hallo Welt!')
  68. i18n.setTranslationMap(new Map())
  69. await nextTick()
  70. expect(container).toHaveTextContent('Hello world!')
  71. })
  72. })
  73. })