Set of helpers for testing React-components
Helpers are based on libraries @testing-library/react
If you are using jest for testing, consider to add a library @testing-library/jest-dom
react
should be installed manually
npm i --save-dev @tramvai/test-react
:::caution
Only React >= 18 version is supported
:::
Based on the React act test helper that is used to perform rerender component after start changes.
Put you actions that will update React state inside act
function in order to check result render in the next code.
:::warning
Current wrapper should be awaited in tests to execute some additional internal steps
:::
Under the hood the @testing-library/react is used.
/**
* @jest-environment jsdom
*/
import { testComponent } from '@tramvai/test-react';
describe('test', () => {
it('render', async () => {
const { screen, rerender, context, act, fireEvent, Wrapper } = testComponent(<Cmp id={1} />);
// test component render
expect(screen.getByTestId('test').textContent).toBe('Content 1');
// test render after store update
act(() => {
context.dispatch(event('data'));
});
// interact with the component
fireEvent.click(screen.getByText('Button'));
// component rerender
rerender(<Cmp id={2} />);
expect(screen.getByTestId('test').textContent).toBe('Content 2');
});
});
More examples
@inline src/testComponent.spec.tsx
Under the hood the @testing-library/react is used.
/**
* @jest-environment jsdom
*/
import { testHook } from '@tramvai/test-react';
describe('test', () => {
it('hook', async () => {
const { result, context, act } = testHook(() => useHook());
// test the result of hook call
expect(result.current).toBe('result');
// test the result after store update
act(() => {
context.dispatch(event('data'));
});
});
});
More examples
@inline src/testHook.spec.tsx
@tramvai/test-react
comes with support for react 16 and 17 so if you are using react@18 it will lead to the above warning as this backward-compatibility forces to use legacy render methods.
You can manually specify not to use legacy rendering mode by settings option legacyRoot
to false
/**
* @jest-environment jsdom
*/
import { testComponent } from '@tramvai/test-react';
describe('test', () => {
it('component', async () => {
const { render } = testComponent(<Cmp id={1} />, { legacyRoot: false });
});
});