Skip to content

Commit

Permalink
✨ handle hooks setState with function
Browse files Browse the repository at this point in the history
  • Loading branch information
FBerthelot committed Dec 19, 2019
1 parent ffa2b33 commit 2022724
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const {shallow} = require('../shallow');
const React = require('react');

describe('shallow - react useState', () => {
const Component = () => {
const [state, setState] = React.useState('initialState');
const handleClick = () => {
setState(prevState => `${prevState}+1`);
};

return <button type="button" onClick={handleClick}>{state}</button>;
};

it('should return the initialState correctly', () => {
const cmp = shallow(<Component/>);

expect(cmp.html()).toBe('<button type="button" onClick="[handleClick]">initialState</button>');
});

it('should update the state when cllicking on the button', () => {
const cmp = shallow(<Component/>);

cmp.dispatchEvent('click');

expect(cmp.html()).toBe('<button type="button" onClick="[handleClick]">initialState+1</button>');
});
});
7 changes: 6 additions & 1 deletion packages/component-test-utils-react/src/dispatcher/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@ class Dispatcher {
}

useState(initialState) {
return this.useReducer((_, arg) => arg, initialState);
return this.useReducer(
(prevState, arg) => {
return typeof arg === 'function' ? arg(prevState) : arg;
},
initialState
);
}

useEffect(fn, memo) {
Expand Down

0 comments on commit 2022724

Please sign in to comment.