mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Enable theme context mocking in tests (#20519)
* Enable theme context mocking in tests * Expose mockThemeContext from grafana/ui * Add docs * Update contribute/style-guides/themes.md Co-Authored-By: Marcus Olsson <olsson.e.marcus@gmail.com> * Update packages/grafana-ui/src/themes/ThemeContext.tsx Co-Authored-By: Marcus Olsson <olsson.e.marcus@gmail.com> * Update contribute/style-guides/themes.md Co-Authored-By: Marcus Olsson <olsson.e.marcus@gmail.com> * Docs update * Update contribute/style-guides/themes.md Co-Authored-By: Marcus Olsson <olsson.e.marcus@gmail.com>
This commit is contained in:
@@ -29,7 +29,7 @@ const Foo: React.FunctionComponent<FooProps> = () => {
|
||||
|
||||
```
|
||||
|
||||
#### Using `withTheme` HOC
|
||||
#### Using `withTheme` higher-order component (HOC)
|
||||
|
||||
With this method your component will be automatically wrapped in `ThemeContext.Consumer` and provided with current theme via `theme` prop. Component used with `withTheme` must implement `Themeable` interface.
|
||||
|
||||
@@ -43,6 +43,36 @@ const Foo: React.FunctionComponent<FooProps> = () => ...
|
||||
export default withTheme(Foo);
|
||||
```
|
||||
|
||||
### Test components that use ThemeContext
|
||||
|
||||
When implementing snapshot tests for components that use the `withTheme` HOC, the snapshot will contain the entire theme object. Any change to the theme renders the snapshot outdated.
|
||||
|
||||
To make your snapshot theme independent, use the `mockThemeContext` helper function:
|
||||
|
||||
```tsx
|
||||
import { mockThemeContext } from '@grafana/ui';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
let restoreThemeContext;
|
||||
|
||||
beforeAll(() => {
|
||||
// Create ThemeContext mock before any snapshot test is executed
|
||||
restoreThemeContext = mockThemeContext({ type: GrafanaThemeType.Dark });
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
// Make sure the theme is restored after snapshot tests are performed
|
||||
restoreThemeContext();
|
||||
});
|
||||
|
||||
it('renders correctyl', () => {
|
||||
const wrapper = mount(<MyComponent />)
|
||||
expect(wrapper).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Using themes in Storybook
|
||||
|
||||
All stories are wrapped with `ThemeContext.Provider` using global decorator. To render `Themeable` component that's not wrapped by `withTheme` HOC you either create a new component in your story:
|
||||
|
||||
Reference in New Issue
Block a user