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

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

我在构建单元测试以检查 Antd 菜单中的 href 链接是否指向正确位置时遇到问题。我将 antd 菜单与包含两个下拉项的子菜单一起使用。单击其中任何一个时,它们都会转到各自的网址。这是我的 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');
  });
});