I'm having trouble building unit tests to check if my a href links in my Antd Menu are going to the right places. I used the antd Menu with SubMenu that contains two dropdown items. When either one is clicked, they go to their respective urls. Here is my 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>
}
Here is what I'm trying in my App.test.js unit test
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');
});
});
I've also tried:
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');
});
});
Neither of these methods work and I feel like I've tried everything I could find through documentation and other stack overflow posts.
First: Submenu are hidden from initialy, and any children of them is not present in VDOM, so you need to fire mouseover
to make sub-menu items rendered: fireEvent.mouseOver(getByText('Google Links'));
Next, the firaEvent
are async, so you need to await for it complete, something like: await waitFor(() => getByText('Homepage Link'));
And all together:
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');
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.