Skip to content

Commit

Permalink
test(Theme): increase test coverage to 100% (#17888)
Browse files Browse the repository at this point in the history
* test(Theme): increase test coverage to 100%

* test: add tests for Global Theme function

* test: add tests for usePrefersDarkScheme function

* test: addressed review comments

---------

Co-authored-by: Preeti Bansal <[email protected]>
  • Loading branch information
Shankar-CodeJunkie and preetibansalui authored Oct 29, 2024
1 parent c3b777a commit e053b7f
Showing 1 changed file with 51 additions and 1 deletion.
52 changes: 51 additions & 1 deletion packages/react/src/components/Theme/__tests__/Theme-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
*/

import React from 'react';
import { Theme, useTheme } from '../../Theme';
import {
Theme,
useTheme,
GlobalTheme,
usePrefersDarkScheme,
} from '../../Theme';
import { screen, render } from '@testing-library/react';
import * as hooks from '../../../internal/useMatchMedia';

Expand Down Expand Up @@ -90,4 +95,49 @@ describe('usePrefersDarkScheme', () => {

expect(screen.getByTestId('default')).toHaveTextContent('dark');
});

it('should call usePrefersDarkScheme', () => {
jest.resetModules();
usePrefersDarkScheme(); //mock the function

jest.spyOn(hooks, 'useMatchMedia').mockImplementation(() => false);
render(
<Theme theme="g10">
<DarkTestComponent id="default-dark" />
</Theme>
);

expect(screen.getByTestId('default-dark')).toHaveTextContent('light');
expect(hooks.useMatchMedia).toHaveBeenCalledWith(
'(prefers-color-scheme: dark)'
);
});
});

describe('GlobalTheme', () => {
it('should set the theme globally', () => {
jest.resetModules();
function TestComponent({ id }) {
const { theme } = useTheme();
return (
<span className="test" data-testid={id}>
{theme}
</span>
);
}

const { container } = render(
<GlobalTheme theme="white">
<TestComponent id="default" />
</GlobalTheme>
);

expect(screen.getByTestId('default')).toHaveTextContent('white');
//it does not have any styles or class name like cds--white
const divElement = screen.getByTestId('default');
const hasCarbonClassName = Array.from(divElement.classList).some(
(className) => className.startsWith('cds--')
);
expect(hasCarbonClassName).toBe(false);
});
});

0 comments on commit e053b7f

Please sign in to comment.