简体   繁体   English

如何使用 React-testing-library 或 jest 在反应路由器中测试通过 Link 传递的道具

[英]how to test props which is pass through Link in react router with React-testing-library or jest

how do I test props which is pass to other page as given below I have created a object of name merchant which need to be passed to other page which I am passing as a props in Link.如何测试传递到其他页面的道具,如下所示我已经创建了一个名称商家的 object,需要传递到我作为链接中的道具传递的其他页面。 and accessing value using useLocation and setting to dropdown并使用useLocation访问值并设置为下拉

const {merchantData} = useLocation();

I want to write a test case for this, but how to test it which has passed as props我想为此编写一个测试用例,但是如何测试它已作为道具传递

const merchant = {
value:"abc123",
label:"abc",
data:{
   id:1,
   name:abc
  }
}
<Link to={{ pathname: `/administration/person/add`,merchantData: merchant }}> Create Person</Link>

You could mock history.push in your test, then click on your Link , and expect that history.push has been called, with the correct parameters:您可以在测试中模拟history.push ,然后单击您的Link ,并期望使用正确的参数调用history.push

import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

describe('my component', () => {
  beforeEach(() => {
    history.push = jest.fn();
  });

  it('passes correct parameters when following the link', () => {
    rtl = render(
      <Router history={history}>
        <MyComponent />
      </Router>
    );

    // we assume that MyComponent contains the Link you provided
    userEvent.click(rtl.getByText('Create Person'));
    expect(history.push).toHaveBeenCalledWith({
      pathname: '/administration/person/add',
      merchantData: { /* your object */ }
    });
  });
});

But you should pass additional informations in the state property of the to props: https://v5.reactrouter.com/web/api/Link/to-object但是您应该在to道具的 state 属性中传递其他信息: https://v5.reactrouter.com/web/api/Link/to-object

<Link to={{ pathname: `/administration/person/add`, state: { merchant } }}>Create Person</Link>

If you do so, you will need to modify the above test accordingly.如果这样做,则需要相应地修改上述测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM