0

My test is not 100% coverage because I haven't tested the onClick event button. How to do it in react-testing-library? Please note that I use connected-react-router here and I don't know how to write it in my test. If I made any mistakes in the code, I am sorry, but I am still learning to test.

index.js:

import React from 'react';
import { useDispatch } from 'react-redux';
import { push } from 'connected-react-router';
import {
  StyledFooter,
  StyledButton,
} from './Footer.style';


export default function Footer() {
  const dispatch = useDispatch();

  return (
    <StyledFooter>
      <div>
        <StyledButton type="link" onClick={() => dispatch(push('/test'))}>
          test
        </StyledButton>
      </div>
    </StyledFooter>
  );
}

index.test.js:

/**
 *
 * Tests for Footer
 *
 */

import React from 'react';
import { render } from '@testing-library/react';
import { Provider } from 'react-redux';
import { IntlProvider } from 'react-intl';

import { createMemoryHistory } from 'history';
import Footer from '../index';
import { DEFAULT_LOCALE } from '../../../locales';
import configureStore from '../../../configureStore';

describe('<Footer />', () => {
  const history = createMemoryHistory();
  const store = configureStore({}, history);

  it('should render a div', () => {
    const { container } = render(
      <Provider store={store}>
        <IntlProvider locale={DEFAULT_LOCALE}>
          <Footer />
        </IntlProvider>
      </Provider>,
    );
    expect(container.firstChild).toMatchSnapshot();
  });
});

Tests result:

 app/components/Footer           |    87.5 |      100 |      50 |    87.5 |                   
  Footer.style.js                |     100 |      100 |     100 |     100 |                   
  index.js                       |   66.67 |      100 |      50 |   66.67 |                
  messages.js                    |       0 |        0 |       0 |       0 |    

1 Answer 1

2

First you should get the element what you want to click on. For this you can use the getByText function.

import { render, fireEvent } from '@testing-library/react'

const { container, getByText } = render(
      <Provider store={store}>
        <IntlProvider locale={DEFAULT_LOCALE}>
          <Footer />
        </IntlProvider>
      </Provider>,
    );

const button = getByText("test");

Next you have to trigger a click event on the element

fireEvent.click(button)

Then you can assert on the result.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.