[英]react-testing-library: test onClick event
我的测试不是 100% 覆盖率,因为我还没有测试过 onClick 事件按钮。 如何在反应测试库中做到这一点? 请注意,我在这里使用connected-react-router,我不知道如何在我的测试中编写它。 如果我在代码中犯了任何错误,我很抱歉,但我仍在学习测试。
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();
});
});
测试结果:
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 |
首先你应该得到你想要点击的元素。 为此,您可以使用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");
接下来,您必须在元素上触发点击事件
fireEvent.click(button)
然后你可以断言结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.