javascript React-Router:如何测试渲染链接的 href?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30332636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:04:03  来源:igfitidea点击:

React-Router: How to test href of a rendered Link?

javascriptreactjsmochareact-router

提问by Jeff Fairley

I have a React component that renders a <Link/>.

我有一个 React 组件,它呈现一个<Link/>.

render: function () {
    var record = this.props.record;
    return (
        <Link to="record.detail" params={{id:record.id}}>
            <div>ID: {record.id}</div>
            <div>Name: {record.name}</div>
            <div>Status: {record.status}</div>
        </Link>
    );
}

I can easily obtain the rendered <a/>, but I'm not sure how to test that the href was built properly.

我可以轻松获得渲染的<a/>,但我不确定如何测试 href 是否正确构建。

function mockRecordListItem(record) {
    return stubRouterContext(require('./RecordListItem.jsx'), {record: record});
}
it('should handle click', function () {
    let record = {id: 2, name: 'test', status: 'completed'};
    var RecordListItem = mockRecordListItem(record);
    let item = TestUtils.renderIntoDocument(<RecordListItem/>);

    let a = TestUtils.findRenderedDOMComponentWithTag(item, 'a');
    expect(a);

    // TODO: inspect href?
    expect(/* something */).to.equal('/records/2');
});

Notes: The stubRouterContextis necessary in React-Router v0.13.3 to mock the <Link/>correctly.

注:stubRouterContext是阵营,路由器v0.13.3必要嘲笑<Link/>正确。

Edit:

编辑:

Thanks to Jordanfor suggesting a.getDOMNode().getAttribute('href'). Unfortunately when I run the test, the result is null. I expect this has to do with the way stubRouterContextis mocking the <Link/>, but how to 'fix' is still TBD...

感谢Jordan的建议a.getDOMNode().getAttribute('href')。不幸的是,当我运行测试时,结果是null. 我希望这与stubRouterContext嘲笑的方式有关<Link/>,但是如何“修复”仍然是待定的......

回答by Kateika

I use jest and enzyme for testing. For Link from Route I use Memory Router from their official documentation https://reacttraining.com/react-router/web/guides/testing

我使用笑话和酶进行测试。对于来自路由的链接,我使用了他们官方文档中的内存路由器https://reacttraining.com/react-router/web/guides/testing

I needed to check href of the final constructed link. This is my suggestion:

我需要检查最终构建的链接的 href。这是我的建议:

MovieCard.js:

MovieCard.js:

export function MovieCard(props) {
  const { id, type } = props;
  return (
    <Link to={`/${type}/${id}`} className={css.card} />
  )
};

MovieCard.test.js (I skip imports here):

MovieCard.test.js(我在这里跳过导入):

const id= 111;
const type= "movie";

test("constructs link for router", () => {
    const wrapper = mount(
      <MemoryRouter>
        <MovieCard type={type} id={id}/>
      </MemoryRouter>
    );

    expect(wrapper.find('[href="/movie/111"]').length).toBe(1);
  });

回答by Jeff Fairley

Ok. This simply took some digging into the stubRouterContextthat I already had.

行。这只是对stubRouterContext我已经拥有的进行了一些挖掘。

The third constructor argument, stubs, is what I needed to pass in, overriding the default makeHreffunction.

第三个构造函数参数 ,stubs是我需要传入的参数,覆盖默认makeHref函数。

Working example:

工作示例:

function mockRecordListItem(record, stubs) {
    return stubRouterContext(require('./RecordListItem.jsx'), {record: record}, stubs);
}
it('should handle click', function () {
    let record = {id: 2, name: 'test', status: 'completed'};
    let expectedRoute = '/records/2';
    let RecordListItem = mockRecordListItem(record, {
        makeHref: function () {
            return expectedRoute;
        }
    });
    let item = TestUtils.renderIntoDocument(<RecordListItem/>);
    let a = TestUtils.findRenderedDOMComponentWithTag(item, 'a');
    expect(a);

    let href = a.getDOMNode().getAttribute('href');
    expect(href).to.equal(expectedRoute);
});

It was right there in front of me the whole time.

它一直就在我面前。

回答by Jordan Running

You can use a.getDOMNode()to get the acomponent's DOM node and then use regular DOM node methods on it. In this case, getAttribute('href')will return the value of the hrefattribute:

您可以使用a.getDOMNode()获取a组件的 DOM 节点,然后在其上使用常规 DOM 节点方法。在这种情况下,getAttribute('href')将返回href属性的值:

let a = TestUtils.findRenderedDOMComponentWithTag(item, 'a');
let domNode = a.getDOMNode();

expect(domNode.getAttribute('href')).to.equal('/records/2');