Reputation: 123
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 |
Upvotes: 0
Views: 14318
Reputation: 589
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.
Upvotes: 2