0

Very new to React Testing Library and I am lost to test the input component from Material UI and have access to the value. I only want to test the input value correctly and check if a button is disabled after the user inputs texts. However I keep getting errors on the onChange callback function, handleSearchInput. Any help is appreciated.

App.js

import React, { useContext } from "react";
import { GlobalContext } from "./context/GlobalState";
import "./App.css";
import API from "./utils/API";
import Post from "./components/Post"
import Container from "@material-ui/core/Container";
import Button from "@material-ui/core/Button";
import Box from "@material-ui/core/Box";
import Input from "@material-ui/core/Input";
import { Typography } from "@material-ui/core";

function App() {
  const {
    searchInput,
    handleSearchInput,
    handleResults,
    Results,
    startIndex,
    endIndex,
    decreasePageIndex,
    increasePageIndex,
    clearSearch,
  } = useContext(GlobalContext);

  const formattedInput = searchInput.split(" ").join("");
  return (
    <Container id="red-container">
      <Container id="search-container">
        <Box id="search-box">
            <Input
              type="text"
              id="standard-basic"
              onChange={(event) => {
                 handleSearchInput(event.target.value);
               }}
              placeholder="Search..."
            />
            <Button
            type="submit"
            disabled={searchInput ? false : true}
            onClick={() => {
              clearSearch();
              API.getPosts(formattedInput).then((res) => {
                const posts= res;
                handleResults(posts);
              });
            }}
            variant="contained"
          >
            Search
          </Button>
        </Box>
      </Container>
      {Results.length > 0 ? (
        <Container>
          <Container id="pagination-container">
            <Box component="span"> Results </Box>
            <Box>
              <Button
                variant="outlined"
                disabled={startIndex === 0}
                onClick={() => {
                  decreasePageIndex();
                }}
              >
                {"<"}
              </Button>
              <Button
                variant="outlined"
                disabled={endIndex >= Results.length - 1}
                onClick={() => {
                  increasePageIndex();
                }}
              >
                {">"}
              </Button>
            </Box>
          </Container>
          {Results
            .filter((postObj) => {
              return postObj.key >= startIndex && postObj.key < endIndex;
            })
            .map(
              (postObj) => (
                <Post key={postObj.key} postObj={postObj} />
              )
            )}
        </Container>
      ) : null}
    </Container>
  );
}

export default App;

App.test.js

  test("Search is enabled after text input", async () => {
    render(<App />);
    const handleSearchInput = jest.fn()
    const input = screen.getByPlaceholderText("Search...")
    const button = screen.getByRole("button")
    expect(button).toBeDisabled();
    fireEvent.change(input, { target: { value: 'meme' } })
    expect(button).not.toBeDisabled();
    expect(searchInput.value).toBe('meme')
  });
});

error:

    TypeError: handleSearchInput is not a function

      33 |               id="standard-basic"
      34 |               onChange={(event) => {
    > 35 |                 handleSearchInput(event.target.value);
         |                 ^
      36 |               }}
      37 |               placeholder="Search..."
      38 |             />
3
  • 1
    Can you please share your App.js code ? Once you do I'll be able to help ! Commented Aug 8, 2021 at 19:06
  • Oh now I understand. So it says handleSearchInput is not a function. It seems like your GlobalContext may not be providing the function. Can you check that context to see that its actually defined correctly. Is it ? Commented Aug 9, 2021 at 9:49
  • @Bahdcoder it is defined correctly. I don't know how to gain access to it from testing it using the react testing library Commented Aug 9, 2021 at 12:00

1 Answer 1

1

In order to access the values from your context in your test file, you need to wrap the component you're rendering with your context:

import { GlobalContext } from './path-to-context';

test("Search is enabled after text input", async () => {
  render(<GlobalContext><App /></GlobalContext>);

  // ...the rest of your test file
});

It might also be helpful to create a function for rendering with the GlobalContext depending on how many tests you're using it in, ex:

const renderWithContext = (ui) => {
  return render(<GlobalContext>{ui}</GlobalContext>);
}

renderWithContext(<App />);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.