我有一个使用React.useState()来管理抽屉模式状态的功能组件。我想用玩笑的酶测试该状态的变化,但是我不能称其为状态函数,因为它不是类组件。
我要测试的代码如下:
--unbuffered
fifo=/tmp/fifo.$$
mkfifo $fifo
tail -f $fifo | mysql --unbuffered -u root -N > /tmp/sql.log &
echo "SELECT IF(GET_LOCK('foo',1)=1,'Got lock', concat('Already locked by connection: ', IS_USED_LOCK('foo')));" >$fifo
# sleep to prove that the fifo isn't closed for later queries
sleep 10
echo "SELECT CONNECTION_ID();" >$fifo
# /tmp/sql.log has results of both sql queries
如果这是一个类组件,这将是可行的:
const [state, setState] = React.useState({
drawerOpen: false,
});
function toggleDrawer(boolean) {
setState({ ...state, drawerOpen: boolean });
}
是的,它应该仍然是功能组件。
答案 0 :(得分:0)
也许会有所帮助: 这是一个模拟工具,基本上是一个将接受状态并返回元组的函数
export const setHookState = (newState: {}) => jest.fn().mockImplementation((state: {}) => [
newState,
(newState: {}) => {}
])
然后,在测试中,您可以像这样使用它:
import { setHookState } from 'utils/test'
import { ComponentWithHook } from './ComponentWithHook'
import { NeededComponent } from './NeededComponent'
const reactMock = require('react')
describe('ComponentWithHook component', () => {
it('should render itself', () => {
reactMock.useState = setHookState({
data: [],
isFetching: false
})
const wrapper = shallow(<ComponentWithHook/>)
expect(wrapper.find(<NeededComponent>).exists()).toEqual(true)
})
})
此来源的信息:here