I want to test an input field with jest and enzyme
test('Filter Test', async () => {
const setFilter = jest.fn();
const bar = mount(
<TestWrapper>
<SearchAndFilterBar textFilters={textFilters} filterButtons={filterButtons} setFilterQuery={setFilter} />
</TestWrapper>,
);
bar
.find('#minValue')
.simulate('change', { target: { value: '23' } })
.simulate('keypress', { key: 'Enter', code: 13 });
expect(setFilter).toHaveBeenCalled();
});
the code is the following
<TextInput
onKeyPress={onMinKeyPressHandler}
id={'minValue'}
invalid={false}
value={minValue}
onChange={e => !isNaN(Number(e.target.value)) && setMinValue(e.target.value)}
placeholder={valueType}
/>
The problem is that the onMinKeyPressHandler is not called called by the test.
Does someone see why the test is not working?
I'm not able to replicate your issue. That said, I think you can simplify your component to, instead of being a
text
input, being anumber
input.By setting
type="number"
and adding amin="0"
, you can skip checking whether or not it's a valid number in youronChange
callback.I created a codesandbox with working tests (click the
Tests
tab to run the tests):If your set up is different, fork the codesandbox, adjust it as needed and add it in the comments below.
components/Input/index.js
components/Input/__tests__/Input.test.js