![](/img/trans.png)
[英]React Jest/Enzyme Testing: useHistory Hook Breaks Test
[英]How to test React component that uses React Hooks useHistory hook with Enzyme?
我正在嘗試使用酶測試 React 組件。 測試工作正常,直到我們將組件轉換為鈎子。 現在我收到錯誤消息,“錯誤:未捕獲 [TypeError:無法讀取未定義的屬性‘歷史’]”
我已經閱讀了以下類似的問題,但無法解決:
完整組件,AccessBarWithRouter.jsx:
/**
* @description Accessibility bar component to allow user to jump focus to different components on screen.
* One dropdown will focus to elements on screen.
* The other will route you to routes in your navigation bar.
*
*/
import React, { useState, useEffect, useRef } from 'react';
import Dropdown from 'react-dropdown-aria';
import { useHistory } from 'react-router-dom';
const AccessBarWithRouter = () => {
const pathname = useHistory().location.pathname;
const [sectionInfo, setSectionInfo] = useState(null);
const [navInfo, setNavInfo] = useState(null);
const [isHidden, setIsHidden] = useState(true);
// creating the refs to change focus
const sectionRef = useRef(null);
const accessBarRef = useRef(null);
// sets focus on the current page from the 1st dropdown
const setFocus = e => {
const currentLabel = sectionInfo[e];
const currentElement = document.querySelector(`[aria-labelledBy='${currentLabel}']`);
currentElement.tabIndex = -1;
sectionRef.current = currentElement;
// can put a .click() after focus to focus with the enter button
// works, but gives error
sectionRef.current.focus();
};
// Changes the page when selecting a link from the 2nd dropdown
const changeView = e => {
const currentPath = navInfo[e];
const accessLinks = document.querySelectorAll('.accessNavLink');
accessLinks.forEach(el => {
if (el.pathname === currentPath) {
el.click();
};
});
};
// event handler to toggle visibility of AccessBar and set focus to it
const accessBarHandlerKeyDown = e => {
if (e.altKey && e.keyCode === 191) {
if (isHidden) {
setIsHidden(false)
accessBarRef.current.focus();
} else setIsHidden(true);
}
}
/**
*
* useEffect hook to add and remove the event handler when 'alt' + '/' are pressed
* prior to this, multiple event handlers were being added on each button press
* */
useEffect(() => {
document.addEventListener('keydown', accessBarHandlerKeyDown);
const navNodes = document.querySelectorAll('.accessNavLink');
const navValues = {};
navNodes.forEach(el => {
navValues[el.text] = el.pathname;
});
setNavInfo(navValues);
return () => document.removeEventListener('keydown', accessBarHandlerKeyDown);
}, [isHidden]);
/**
* @todo figure out how to change the dropdown current value after click
*/
useEffect(() => {
// selects all nodes with the aria attribute aria-labelledby
setTimeout(() => {
const ariaNodes = document.querySelectorAll('[aria-labelledby]');
let sectionValues = {};
ariaNodes.forEach(node => {
sectionValues[node.getAttribute('aria-labelledby')] = node.getAttribute('aria-labelledby');
});
setSectionInfo(sectionValues);
}, 500);
}, [pathname]);
// render hidden h1 based on isHidden
if (isHidden) return <h1 id='hiddenH1' style={hiddenH1Styles}>To enter navigation assistant, press alt + /.</h1>;
// function to create dropDownKeys and navKeys
const createDropDownValues = dropDownObj => {
const dropdownKeys = Object.keys(dropDownObj);
const options = [];
for (let i = 0; i < dropdownKeys.length; i++) {
options.push({ value: dropdownKeys[i]});
}
return options;
};
const sectionDropDown = createDropDownValues(sectionInfo);
const navInfoDropDown = createDropDownValues(navInfo);
return (
<div className ='ally-nav-area' style={ barStyle }>
<div className = 'dropdown' style={ dropDownStyle }>
<label htmlFor='component-dropdown' tabIndex='-1' ref={accessBarRef} > Jump to section: </label>
<div id='component-dropdown' >
<Dropdown
options={ sectionDropDown }
style={ activeComponentDDStyle }
placeholder='Sections of this page'
ariaLabel='Navigation Assistant'
setSelected={setFocus}
/>
</div>
</div>
<div className = 'dropdown' style={ dropDownStyle }>
<label htmlFor='page-dropdown'> Jump to page: </label>
<div id='page-dropdown' >
<Dropdown
options={ navInfoDropDown }
style={ activeComponentDDStyle }
placeholder='Other pages on this site'
ariaLabel='Navigation Assistant'
setSelected={ changeView }
/>
</div>
</div>
</div>
);
};
/** Style for entire AccessBar */
const barStyle = {
display: 'flex',
paddingTop: '.1em',
paddingBottom: '.1em',
paddingLeft: '5em',
alignItems: 'center',
justifyContent: 'flex-start',
zIndex: '100',
position: 'sticky',
fontSize: '.8em',
backgroundColor: 'gray',
fontFamily: 'Roboto',
color: 'white'
};
const dropDownStyle = {
display: 'flex',
alignItems: 'center',
marginLeft: '1em',
};
/** Style for Dropdown component **/
const activeComponentDDStyle = {
DropdownButton: base => ({
...base,
margin: '5px',
border: '1px solid',
fontSize: '.5em',
}),
OptionContainer: base => ({
...base,
margin: '5px',
fontSize: '.5em',
}),
};
/** Style for hiddenH1 */
const hiddenH1Styles = {
display: 'block',
overflow: 'hidden',
textIndent: '100%',
whiteSpace: 'nowrap',
fontSize: '0.01px',
};
export default AccessBarWithRouter;
這是我的測試,AccessBarWithRouter.unit.test.js:
import React from 'react';
import Enzyme, { mount } from 'enzyme';
import AccessBarWithRouter from '../src/AccessBarWithRouter.jsx';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
describe('AccessBarWithRouter component', () => {
it('renders hidden h1 upon initial page load (this.state.isHidden = true)', () => {
const location = { pathname: '/' };
const wrapper = mount(
<AccessBarWithRouter location={location}/>
);
// if AccessBarWithRouter is hidden it should only render our invisible h1
expect(wrapper.exists('#hiddenH1')).toEqual(true);
})
it('renders full AccessBarWithRouter when this.state.isHidden is false', () => {
// set dummy location within test to avoid location.pathname is undefined error
const location = { pathname: '/' };
const wrapper = mount(
<AccessBarWithRouter location={location} />
);
wrapper.setState({ isHidden: false }, () => {
// If AccessBar is not hidden the outermost div of the visible bar should be there
// Test within setState waits for state change before running test
expect(wrapper.exists('.ally-nav-area')).toEqual(true);
});
});
});
我是 React Hooks 的新手,所以我試圖圍繞它進行思考。 我的理解是我必須為我的測試提供某種模擬歷史值。 我嘗試創建一個單獨的 useContext 文件,並在測試中將其包裹在我的組件周圍,但這不起作用:
import React, { useContext } from 'react';
export const useAccessBarWithRouterContext = () => useContext(AccessBarWithRouterContext);
const defaultValues = { history: '/' };
const AccessBarWithRouterContext = React.createContext(defaultValues);
export default useAccessBarWithRouterContext;
我當前的 devDependencies 版本:
我沒有找到很多文檔來測試一般使用 useHistory 鈎子的組件。 似乎 Enzyme 一年前才開始使用 React Hooks,並且只用於模擬,而不是用於淺層渲染。
任何人都知道我該怎么做?
正如您可以想象的那樣,這里的問題來自 useHistory 鈎子內部。 該鈎子旨在用於路由器提供商的消費者。 如果您知道 Providers 和 Consumers 的結構,那么對您來說很有意義,這里的消費者 (useHistory) 試圖從提供者訪問一些信息,而這些信息在您的文本案例中不存在。 有兩種可能的解決方案:
用路由器包裝你的測試用例
it('renders hidden h1 upon initial page load (this.state.isHidden = true)', () => { const location = { pathname: '/' }; const wrapper = mount( <Router> <AccessBarWithRouter location={location}/> </Router> ) });
使用假歷史數據模擬 useHistory 鈎子
jest.mock('react-router-dom', () => { const actual = require.requireActual('react-router-dom') return { ...actual, useHistory: () => ({ methods }), } })
我個人更喜歡第二個,因為您可以將它放在 setupTests 文件中並忘記它。 如果您需要模擬或監視它,您可以在您的特定單元測試文件中覆蓋 setupTests 文件中的模擬。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.