React testing library mock function to onclick of button is not called

Viewed 894

Im testing API calls made from a form using react-testing-library and jest. I have used formik in the form. Here in the test written it fails saying the that function "mockCreateItem" has not been called.

Then as a way of debugging I created the spy and I tried sending the spy I have defined as a prop to the component and invoking it on the onClick event. When the onClick ={test} was directly equal to the test this worked. But when test was called within the onSubmit function it failed saying no function call is made Am I doing this wrong. Any suggestions to make this work is really helpful. Thank you


import { Formik } from "formik";
import {createItem} from "../../api/item";

const ItemForm = ({test}) => {
  let initialValues = {
    Name: "",
  };

  return (
    <Box>
      <Formik
        initialValues={initialValues}
        onSubmit={async (values) => {
          let result = await createItem(values);
          //test();
        }}
      >
        {(props) => (
          <Box>
              <FormControl>
                <FormLabel>Name</FormLabel>
                <Input
                  type="text"
                  name="Name"
                  value={props.initialValues.Name}
                  {...props.getFieldProps("Name")}
                />
                
              </FormControl>
              <Button onClick={props.submitForm} id="item_form_submit">
                Submit
              </Button>
          </Box>
        )}
      </Formik>
    </Box>
  );
};

Test code

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import ItemForm from "../../../components/forms/item_form.jsx";
import * as ItemAPI from "../../../api/item.jsx";


describe("item form tests", () =>{
    test("add new item,", () =>{
        let mockCreateItem = jest.spyOn(itemAPI, "createItem").mockImplementation((obj) => obj);
        let spy = jest.fn().mockImplementation((obj) => obj);

        render(<ItemForm test={spy}/>)
        const name = screen.getByRole('textbox',{name:"Name"})
        const submit = screen.getByRole('button',{id:"item_form_submit"})
        fireEvent.change(name,{target:{value:"Kitchen Item"}})
        fireEvent.click(submit);
        expect(mockCreateItem).toHaveBeenCalledTimes(1)
        expect(mockCreateItem).toHaveBeenCalledWith({Name:"Kitchen Item"})
        //expect(spy).toHaveBeenCalledTimes(1)
    })

})
0 Answers
Related