@tramvai/test-react
TypeScript icon, indicating that this package has built-in type declarations

3.40.28 • Public • Published

Tramvai test React

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

Installation

npm i --save-dev @tramvai/test-react

:::caution

Only React >= 18 version is supported

:::

Explanation

act

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

:::

How to

Test component

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

Test React-hooks

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

Troubleshooting

Warning: ReactDOM.render is no longer supported in React 18

@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 });
  });
});

Readme

Keywords

none

Package Sidebar

Install

npm i @tramvai/test-react

Weekly Downloads

118

Version

3.40.28

License

Apache-2.0

Unpacked Size

14.4 kB

Total Files

11

Last publish

Collaborators

  • meskill
  • super_oleg
  • tinkoffbank