[英]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.