Easy to test
Testing components made with morfeo it's pretty easy, let's give some examples in different frameworks to make it clear:
info
The following examples are made using jest
and @testing-library/react
and the components are made in React
but you can apply the same rules and principles to other frameworks too.
Example #1
Given the following component:
Button.tsx
import { useClassName } from '@morfeo/react';
export const Button = ({ children }) => {
const className = useClassName({ componentName: 'Button' });
return <button className={className}>{children}</button>;
};
We can write a simple test to ensure that the style of our button is the same as the one defined inside the theme
Button.spec.tsx
import { morfeo } from '@morfeo/react';
import { render, screen } from '@testing-library/react';
import { Button } from './Button';
beforeAll(() => {
morfefo.setTheme('default', {
colors: {
primary: 'blue',
},
components: {
Button: {
style: {
bg: 'primary',
},
},
},
});
});
test('should have the style defined inside the theme', () => {
render(<Button>Button test</Button>);
const button = screen.getByText(/Button test/i);
expect(button).toHaveStyle('background-color: blue');
});
Example #2
The following component is used to switch the theme from light to dark and vice-versa:
ThemeToggle.tsx
import { useState, useCallback } from 'react';
import { Theme, morfeo, useCurrentTheme } from '@morfeo/react';
import { Button } from './Button';
export const ThemeToggle: React.FC = () => {
const [currentTheme, setCurrentTheme] = useCurrentTheme();
const isLight = currentTheme === 'light';
const onClick = () => {
setCurrentTheme(isLight ? 'dark' : 'light');
};
return <Button onClick={onClick}>{isLight ? `🌙` : `☀️`}</Button>;
};
We can test if the button is working properly with the following test:
ThemeToggle.spec.tsx
import { morfeo } from '@morfeo/react';
import { render, screen, fireEvent } from '@testing-library/react';
import { ThemeToggle } from './ThemeToggle';
const dark = {
colors: {
primary: 'black',
},
};
const light = {
colors: {
primary: 'white',
},
};
beforeAll(() => {
morfeo.setTheme('light', light);
morfeo.setTheme('dark', dark);
});
beforeEach(() => {
morfeo.setCurrentTheme('light', dark);
});
test('should be light by default', () => {
render(<ThemeToggle />);
const button = screen.getByText(/🌙/i);
expect(button).toBeDefined();
expect(morfeo.getTheme().colors.primary).toBe('white');
});
test('should switch the theme to `dark` after the click', () => {
render(<ThemeToggle />);
const button = screen.getByText(/🌙/i);
fireEvent(
button,
new MouseEvent('click', {
bubbles: true,
cancelable: true,
}),
);
expect(morfeo.getTheme().colors.primary).toBe('black');
});