Created
November 10, 2018 21:12
-
-
Save granmoe/1316210dd63fc09bb012acfbcd0e28a8 to your computer and use it in GitHub Desktop.
A way to test React hooks
This file contains hidden or 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
import React from 'react' | |
import { render, fireEvent } from 'react-testing-library' | |
import useValidation from '..' | |
describe('use-validation', () => { | |
const Test = ({ mockFunc, handleSubmit }) => { | |
const { fields } = useValidation({ | |
fields: { | |
foo: '', | |
bar: '', | |
}, | |
defaultErrorMessage: `Please enter a value`, | |
}) | |
mockFunc({ fields, handleSubmit }) | |
return ( | |
<React.Fragment> | |
<input {...fields.foo} data-testid="foo" /> | |
<input | |
{...fields.bar} | |
data-testid="bar" | |
onChange={e => { | |
fields.bar.onChange(e.target.value) | |
}} | |
/> | |
</React.Fragment> | |
) | |
} | |
const mockFunc = jest.fn() | |
const { getByTestId } = render(<Test mockFunc={mockFunc} />) | |
const [{ fields }] = mockFunc.mock.calls[0] | |
const fooFuncs = { | |
onChange: fields.foo.onChange, | |
onBlur: fields.foo.onBlur, | |
} | |
const barFuncs = { | |
onChange: fields.bar.onChange, | |
onBlur: fields.bar.onBlur, | |
} | |
test('fields are initialized correctly', () => { | |
expect(mockFunc.mock.calls[0][0].fields).toEqual({ | |
foo: { | |
value: '', | |
touched: undefined, | |
error: 'Please enter a value', | |
...fooFuncs, | |
}, | |
bar: { | |
value: '', | |
touched: undefined, | |
error: 'Please enter a value', | |
...barFuncs, | |
}, | |
}) | |
}) | |
test('values are updated correctly when onChange is called with an event', () => { | |
fireEvent.change(getByTestId('foo'), { | |
target: { | |
value: 'foo value', | |
}, | |
}) | |
expect(mockFunc.mock.calls[1][0].fields.foo.value).toEqual('foo value') | |
}) | |
test('values are updated correctly when onChange is called with a plain value', () => { | |
fireEvent.change(getByTestId('bar'), { | |
target: { | |
value: 'bar value', | |
}, | |
}) | |
expect(mockFunc.mock.calls[2][0].fields.bar.value).toEqual('bar value') | |
}) | |
test('field funcs are cached across renders', () => { | |
// TODO | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment