From 05f1dfc6896d3affa7c494a1b955f230d836a4b7 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Fri, 27 Oct 2023 18:07:45 +0200 Subject: feat: replace next-themes with a custom ThemeProvider To be honest, next-themes was working fine. However since I use a theme provider for Prism code blocks, some code is duplicated between this app and the library. So I prefer to use a custom Provider without the options I don't need. --- .../theme-provider/theme-provider.test.tsx | 78 ++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/utils/providers/theme-provider/theme-provider.test.tsx (limited to 'src/utils/providers/theme-provider/theme-provider.test.tsx') diff --git a/src/utils/providers/theme-provider/theme-provider.test.tsx b/src/utils/providers/theme-provider/theme-provider.test.tsx new file mode 100644 index 0000000..59a72cc --- /dev/null +++ b/src/utils/providers/theme-provider/theme-provider.test.tsx @@ -0,0 +1,78 @@ +import { describe, expect, it } from '@jest/globals'; +import { render, screen as rtlScreen } from '@testing-library/react'; +import { type FC, useContext } from 'react'; +import { getThemeFromSystem } from '../../helpers'; +import { ThemeContext, ThemeProvider } from './theme-provider'; + +const bodyPrefix = 'Current theme is:'; + +const ComponentTest: FC = () => { + const { theme } = useContext(ThemeContext); + + return ( +
+ {bodyPrefix} {theme} +
+ ); +}; + +describe('ThemeProvider', () => { + it('uses the default value when the provider is not used', () => { + const defaultValue = 'system'; + + render(); + + expect(rtlScreen.getByText(new RegExp(bodyPrefix))).toHaveTextContent( + `${bodyPrefix} ${defaultValue}` + ); + }); + + it('provides the given value to its children and set a matching attribute', () => { + const attribute = 'iure'; + const theme = 'dark'; + + const { baseElement } = render( + + + + ); + + expect(rtlScreen.getByText(new RegExp(bodyPrefix))).toHaveTextContent( + `${bodyPrefix} ${theme}` + ); + expect(baseElement.parentElement?.getAttribute(`data-${attribute}`)).toBe( + theme + ); + expect(baseElement.parentElement).toHaveStyle(`color-scheme: ${theme};`); + }); + + it('can resolve the preferred theme from user system settings', () => { + const attribute = 'qui'; + const defaultTheme = 'system'; + const resolvedTheme = getThemeFromSystem(); + + const { baseElement } = render( + + + + ); + + expect(rtlScreen.getByText(new RegExp(bodyPrefix))).toHaveTextContent( + `${bodyPrefix} ${defaultTheme}` + ); + expect(baseElement.parentElement?.getAttribute(`data-${attribute}`)).toBe( + resolvedTheme + ); + expect(baseElement.parentElement).toHaveStyle( + `color-scheme: ${resolvedTheme};` + ); + }); +}); -- cgit v1.2.3