Skip to content

Instantly share code, notes, and snippets.

@granmoe
Last active November 10, 2018 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save granmoe/4d6c8aa24cab87252805c58024c40756 to your computer and use it in GitHub Desktop.
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
// 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