Ad
How Can I Test A Function Of A Function Component That Uses React.useState() Using Jest Enzyme Testing?
I have a function component that uses React.useState() to manage the state of a drawer modal. I want to test the function the changes this state using jest enzyme, but I cannot call it's state function because it's not a class component.
The code I wish to test is below:
const [state, setState] = React.useState({
drawerOpen: false,
});
function toggleDrawer(boolean) {
setState({ ...state, drawerOpen: boolean });
}
<Button
id="openDrawer"
onClick={() => toggleDrawer(true)}
style={{ margin: spacing.small }}
>
<AddIcon />
{buttonText}
</Button>
And this is what would've worked if it was a class component:
it("should open the drawer on button click", () => {
wrapper.find("#openDrawer").simulate("click");
expect(wrapper.state("drawerOpen")).toBetruthy();
});
And yes, it should remain a function component.
Ad
Answer
Maybe it will be helpfull: Here is an mock util, that is basically a function that is going to accept state and return a tuple
export const setHookState = (newState: {}) => jest.fn().mockImplementation((state: {}) => [
newState,
(newState: {}) => {}
])
Then, in test, you just use it like this:
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)
})
})
Info from this source: here
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad