Skip to content

Commit

Permalink
Test language persistence on localstaorage
Browse files Browse the repository at this point in the history
  • Loading branch information
ciremusyoka committed Apr 8, 2024
1 parent a98070e commit 40a30b3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
4 changes: 2 additions & 2 deletions packages/i18n/src/init.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const languageDetectorOptions = {
const languageDetector = new LanguageDetector(null, languageDetectorOptions);
const cachedLang = languageDetector.detect();

// register own custom language that returns configured language if no language is cached
// register custom detector that returns configured language if no language is cached
if (!cachedLang) {
languageDetectorOptions.order.push(customLanguageDetectorName);
const customLanguageDetector = {
Expand All @@ -49,7 +49,7 @@ if (!cachedLang) {
},
};
languageDetector.addDetector(customLanguageDetector);
languageDetector.detect(); // this will now use our registored detector
languageDetector.detect(); // use registered detector
}

newInstance
Expand Down
22 changes: 20 additions & 2 deletions packages/i18n/src/tests/init.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { waitFor, screen, fireEvent, render, cleanup } from '@testing-library/re
import React from 'react';
import { useTranslation } from 'react-i18next';

const { OpensrpWebI18nProvider } = module;

afterAll(() => {
cleanup();
});
Expand Down Expand Up @@ -41,7 +39,23 @@ jest.mock('@opensrp/pkg-config', () => {
};
});

const i18nextLngKey = 'i18nextLng';
let mockStorage = {};
Object.defineProperty(window, 'localStorage', {
value: {
setItem: jest.fn((key, value) => (mockStorage[key] = value)),
getItem: jest.fn((key) => mockStorage[key]),
removeItem: jest.fn((key) => delete mockStorage[key]),
},
});

afterEach(() => {
mockStorage = {};
cleanup();
});

test('loads up the correct resources', async () => {
const { OpensrpWebI18nProvider } = module;
const MockComponent = () => {
const { t, i18n } = useTranslation();
return (
Expand Down Expand Up @@ -72,8 +86,12 @@ test('loads up the correct resources', async () => {
expect(screen.queryByText(/Jambo/)).not.toBeInTheDocument();
});

expect(window.localStorage.getItem(i18nextLngKey)).toBe(undefined);

fireEvent.click(screen.getByText(/change/i));

// selected language is stored on localstarage
expect(window.localStorage.getItem(i18nextLngKey)).toBe('sw_core');
await waitFor(() => {
expect(screen.getByText(/Jambo/)).toBeInTheDocument();
expect(screen.queryByText(/Hello/)).not.toBeInTheDocument();
Expand Down

0 comments on commit 40a30b3

Please sign in to comment.