繁体   English   中英

如何使用 React 测试库在 antd 菜单中测试 Anchor Hrefs

[英]How to Test Anchor Hrefs in an antd Menu with React Testing Library

我在构建单元测试以检查我的 Antd 菜单中的 a href 链接是否转到正确的位置时遇到了麻烦。 我将 antd 菜单与包含两个下拉项的 SubMenu 一起使用。 当任何一个被点击时,他们 go 到他们各自的网址。 这是我的 App.js:

import React from 'react';
import {Menu} from antd;

export default function App(){
    <Menu>
      <Menu.SubMenu key = 'google' title = {"Google Links}>
         <Menu.ItemGroup>
           <Menu.Item><a href = {https://www.google.com/}> Homepage Link </a></Menu.Item>
           <Menu.Item><a href = {https://www.google.com/imghp?hl=en}> Images Link</a</Menu.Item>
         </Menu.ItemGroup>
      </Menu.SubMenu>
    <Menu>
}

这是我在 App.test.js 单元测试中尝试的内容

describe('Google Links', ()=>{
   it('Links Work', () =>{
    const wrapper = shallow(<App/>);
    const menuFound = wrapper.find(Menu)
    menuFound.simulate('click',{key:'google'});
    expect(wrapper.find(Menu).at(0).props().href).toBe('https://www.google.com/');
    expect(wrapper.find(Menu).at(1).props().href).toBe('https://www.google.com/imghp?hl=en');
    });
});

我也试过:

describe('Google Links', ()=>{
   it('Links Work', () =>{
    const {getByText} = render(<App/>);
    expect(getByText('Homepage Link')).toHaveAttribute('href','https://www.google.com/');
    expect(getByText('Images Link)).toHaveAttribute('href','https://www.google.com/imghp?hl=en');
    });
});

这些方法都不起作用,我觉得我已经尝试了通过文档和其他堆栈溢出帖子找到的所有内容。

首先:子菜单在初始时是隐藏的,并且它们的任何子菜单都不存在于 VDOM 中,因此您需要触发mouseover以渲染子菜单项: fireEvent.mouseOver(getByText('Google Links'));

接下来, firaEvent是异步的,因此您需要等待它完成,例如: await waitFor(() => getByText('Homepage Link'));

一起:

describe('Google Links', () => {
  it('Links Work', async () => {
    const { getByText } = render(<App />);

    fireEvent.mouseOver(getByText('Google Links'));
    await waitFor(() => getByText('Homepage Link'));

    expect(getByText('Homepage Link').href).toEqual('https://www.google.com/');
    expect(getByText('Images Link').href).toEqual('https://www.google.com/imghp?hl=en');
  });
});

暂无
暂无

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

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