i have a component FilterInput that will take two props query and handle_input_change. this will filter the data based on value in input field.
i am writing unit test to check if it filters data based on the string entered in the input field using react testing library like below,
const data_mock = () => {
return {
data: [
{"id":2,"description":"S", "start date": "2019-03-2"},
{"id":1,"description":"something","start date":"2013-06-
14T00:00:00+00:00",}
],
};
};
test('filters the description text', () => {
const mock = data_mock();
const handle_input_change = jest.fn();
const {getByText} = render(
<FilterInput query={""} on_handle_input_change={handle_input_change}>
</FilterInput>);
const search_input_element = document.querySelector('.filter-input');
fireEvent.change(search_input_element, {
target: { value: 'something' },
});
const filtered_text = document.querySelector('.some > div:nth-of -
type(1) > div:nth-of-
type(2)').textContent;
const not_filtered_element = document.querySelector('.rdt_TableBody >
div:nth-of-type(2)');
expect(not_filtered_element).toBeFalsy(); //this element should not be
//visible but is still present
});
below is my code,
class App extends Component {
const handle_input_change = (e) => {
const query = e.target.value;
this.setState(prevState => {
const filtered_data = prevState.project_data.filter(element =>
{
return
element.description.toLowerCase().includes(query.toLowerCase())
||
element.project.toString().toLowerCase().includes(query.toLowerCase());
});
return {
query,
filtered_data
};
});
return (
<FilterInput query={this.state.input} on_handle_input_change=
{this.handle_input_change} />
);
}
now the problem is when i run the test, the even though the query is provided in the input field, the data is not filtered.
i am not sure how to mock on_handle_input_change method for FilterInput component.
could someone help me fix this. thanks.
Instead of using the document directly, you can use container
Please try the above code.