如何使用Jest&酶
const TheComponent = () => {
const [setActive, setActiveState] = useState('');
const [setHeight, setHeightState] = useState('0px');
const content = useRef(null);
const toggleExpand = () => {
setActiveState(setActive === '' ? 'active' : '');
setHeighState(setActive === 'active' ? '0px' : `${content.current.scrollHeight}px`);
};
return (
<div>
<div ref={content} style={{maxHeight: `${setHeight}`}}>
</div>
<button onClick={toggleExpand}>
<span className={`text ${setActive === 'active' ? 'active' : 'disabled'} `}>Collapse</span>
<span className={`text ${setActive === '' ? 'active' : 'disabled'} `}>Expand</span>
</button>
</div>
);
}
让我失望的是,在toggleExpand-onClick上同时调用setActiveState和setHeightState,我也不知道如何传入或模拟内容。current.sollHeight
测试块内部
React.useState = jest.fn(
(
使mock返回一个可以像useState返回值被破坏一样被破坏的数组,
React.useState
.mockReturnValueOnce([true, () => console.log("setState")])
.mockReturnValueOnce(["5ft", () => console.log("setHeight")]);
当对useState进行第一次调用时,链接mockReturnValueOnce将返回第一个,当对useState进行第二次调用时返回第二个。