2

The component that I am trying to test is having state isSubmitting which is set true when we try to submit the form and then it is set back to false when we receive the response from server.

I want to test the state of component after each state update.

const Component = () => {
  const [isSubmitting, setIsSubmitting] = useState();

  const handlePress = async () => {
      setIsSubmitting(true);
      await submitForm();
      setIsSubmitting(false);
  };

  return (
    <>
      <button onPress={() => this.handlePress} />
      {isSubmitting && <IsSubmitting />}
    </>
  )
}

I am able to test only the first component state eg. when I update isSubmitting to true.

import React from 'react';
import { act, create } from 'react-test-renderer';
import Component from './Component';

it('shows loading screen after submit, and hides it after', async () => {
  jest.spyOn(form, 'submitForm').mockResolvedValue();

  const wrapper = create(<Component />);

  act(() => {
    wrapper.root.findByType(Button).props.onPress();
  });

  expect(wrapper.root.findByType(IsSubmitting)).toBeDefined();
});

How can I check that the IsSubmitting component is hidden afterwards? I am also getting an error for not wrapping update into act().

  console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:104
    Warning: An update to Component inside a test was not wrapped in act(...).

    When testing, code that causes React state updates should be wrapped into act(...):

    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */

    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/docs/test-utils.html#act
        in Component

1 Answer 1

2

I had to call act function twice. For the first time without await and for the second time with async await.

  const wrapper = create(<Component />);

  act(() => {
    wrapper.root. findByType(Button).props.onPress();
  });

  expect(wrapper.root.findByType(IsSubmitting)).toBeDefined();

  await act(async () => {});

  expect(wrapper.root.findAllByType(IsSubmitting)).toStrictEqual([]);'

This way, I am able to test component in both states.

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.