Last active
November 10, 2018 21:21
-
-
Save granmoe/4d6c8aa24cab87252805c58024c40756 to your computer and use it in GitHub Desktop.
A weird way of testing react hooks. It's interesting that it's possible, but you should do this instead: https://gist.github.com/granmoe/1316210dd63fc09bb012acfbcd0e28a8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I like how this approach lets me test my hook as if it's a pure function, | |
// but something about this feels weird 🤔 🤫 | |
test('use-validation', () => { | |
let counter = 0 | |
render( | |
<Test> | |
{fields => { | |
const fooFuncs = { | |
onChange: fields.foo.onChange, | |
onBlur: fields.foo.onBlur, | |
} | |
const barFuncs = { | |
onChange: fields.bar.onChange, | |
onBlur: fields.bar.onBlur, | |
} | |
switch (counter) { | |
case 0: | |
expect(fields).toEqual({ | |
foo: { | |
value: '', | |
touched: undefined, | |
error: 'Please enter a value', | |
...fooFuncs, | |
}, | |
bar: { | |
value: '', | |
touched: undefined, | |
error: 'Please enter a value', | |
...barFuncs, | |
}, | |
}) | |
fields.foo.onChange('foo') | |
break | |
case 1: | |
expect(fields).toEqual({ | |
foo: { | |
value: 'foo', | |
touched: undefined, | |
error: null, | |
...fooFuncs, | |
}, | |
bar: { | |
value: '', | |
touched: undefined, | |
error: 'Please enter a value', | |
...barFuncs, | |
}, | |
}) | |
fields.bar.onChange('bar') | |
break | |
case 2: | |
expect(fields).toEqual({ | |
foo: { | |
value: 'foo', | |
touched: undefined, | |
error: null, | |
...fooFuncs, | |
}, | |
bar: { | |
value: 'bar', | |
touched: undefined, | |
error: null, | |
...barFuncs, | |
}, | |
}) | |
fields.foo.onBlur() | |
break | |
case 3: | |
expect(fields).toEqual({ | |
foo: { | |
value: 'foo', | |
touched: true, | |
error: null, | |
...fooFuncs, | |
}, | |
bar: { | |
value: 'bar', | |
touched: undefined, | |
error: null, | |
...barFuncs, | |
}, | |
}) | |
fields.bar.onBlur() | |
break | |
case 4: | |
expect(fields).toEqual({ | |
foo: { | |
value: 'foo', | |
touched: true, | |
error: null, | |
...fooFuncs, | |
}, | |
bar: { | |
value: 'bar', | |
touched: true, | |
error: null, | |
...barFuncs, | |
}, | |
}) | |
break | |
default: | |
break | |
} | |
counter++ | |
return null | |
}} | |
</Test>, | |
) | |
function Test({ children }) { | |
const { fields } = useValidation({ | |
fields: { | |
foo: '', | |
bar: '', | |
}, | |
defaultErrorMessage: `Please enter a value`, | |
}) | |
return children(fields) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment