gpt4 book ai didi

reactjs - 具有 LInk 的组件的 React 单元测试用例

转载 作者:行者123 更新时间:2023-12-02 14:53:04 25 4
gpt4 key购买 nike

我正在尝试为具有 Link

的组件编写单元测试用例

所以,我的组件就像,

 import { Link } from 'react-router-dom';
import { withRouter } from 'react-router-dom'

<div className="col-sm-4">
<Link to="create-job/new" style={{ textDecoration: 'none'}}><button type='button' className="btn btn-lg btn-primary btn-block button-container">Create New Job</button></Link>
</div>
export default withRouter(JobNotFound);

现在,我所做的是,

import JobNotFound from '../JobNotFound';
import { Link } from 'react-router';


describe('JobNotFound Component test cases', () => {

it("renders JobNotFound Component successfully", () => {
const wrapper = shallow(
<JobNotFound />
);
expect(wrapper).toMatchSnapshot();
});

it("simulate the click event on Button", () => {
const onButtonClick = sinon.spy();
const wrapper = shallow(<JobNotFound />);
expect(wrapper.find('Link').prop('to')).to.be.equal('/create-job/new');
});
})

所以,这里我没有得到 Link 元素。谁能帮我解决这个问题?

最佳答案

来自react-router的官方文档:

If you try to unit test one of your components that renders a < Link > or a < Route >, etc. you’ll get some errors and warnings about context. While you may be tempted to stub out the router context yourself, we recommend you wrap your unit test in a < StaticRouter > or a < MemoryRouter >.

这就是您收到错误的原因:

You should not use <Route> or withRouter() outside a <Router>

在测试链路组件时,您应该将它们包装在这些路由器之一中。

例如:

import { MemoryRouter } from 'react-router-dom';
const wrapper = shallow(<MemoryRouter>
<JobNotFound/>
<MemoryRouter/>);

此外,由于您要访问子组件,请尝试使用 mount 而不是 shallow

更新:

我通过了以下测试。

import { Link,MemoryRouter as Router } from 'react-router-dom';

test('simulate the click event on Button', () => {

const onButtonClick = sinon.spy();
const wrapper = mount(<Router><JobNotFound /></Router>);
expect(wrapper.find(Link)).toBeTruthy();
expect(wrapper.find('Link').prop('to')).toEqual('create-job/new');
});

关于reactjs - 具有 LInk 的组件的 React 单元测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54587668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com