ElenLo
ElenLo

Reputation: 47

Component not updating after state change

Please help! I spent the whole day and still can't wrap my head over this test. All I need is to test an error state. I mock my mutation to return an err and then check if there's err alert on the screen. (Everything works fine in browser) Here's my test

    test("Duplicate config error", async () => {
      mockMutation(AddNewConfigDocument, {
        Mutation: {
          addNewConfig: () => {
            throw new Error("A matching configuration already exists.")
          },
        },
      })

      render(<ClauseDetails clauseId={clauseId} />)

      ...
      const createBtn = await screen.findByText("Create")
      expect(createBtn).toBeInTheDocument()
      userEvent.click(createBtn) // this triggers mutation

      expect(await screen.findByText("A matching configuration already exists.", undefined, { timeout: 5000 })).toBeInTheDocument()
    }, 10000)

simplified component

...
  const defaultErrorState = { hasError: false, message: "" }
  const [errorState, setError] = useState<ErrorStateType>(defaultErrorState)

    const onError = (error: ApolloError) => {
     updateErrorState(true, getErrorAlertMessage(error.message))
     refetch()
    }

  const [addNewConfig, { loading }] = useAddNewConfigMutation({
    onError,
    onCompleted,
  })

what I see in the console when running test

    // my mock mutation works
    custom mock response:  {
      "errors": [
        {
          "message": "A matching configuration already exists.",
          "locations": [],
          "path": [
            "addConfig"
          ]
        }
      ],
      "data": {
        "addConfig": null
      }
    }


  console.log
    { errorStateHasError: false }


  console.log
    { errorStateHasError: true }

Then test fails here where err state just realized it has an err on line where I'm trying to findByText("A matching configuration already exists.")

Upvotes: 0

Views: 157

Answers (1)

Muhammad Junaid Ali
Muhammad Junaid Ali

Reputation: 56

yes there is a way you need to get isError from useMutation and create a useEffect.

const {isError} = useMutation()
useEffect(()=>{if(isError){setState()}},[isError])

Upvotes: 1

Related Questions