Enable/disable submit button base on useState boolean values changes true/false using react jest testing library

762 views Asked by At

I am populating the form fields from a configuration and after user updates the fields, I compare the updated fields with configuration fetched earlier using "isEqual". If "isEqual = false" I enable the submit button. I am having little trouble to simulate this behavior using jest. Could anyone help with this test case?

Below is my sample code snippets:

const [areValuesEqual, setAreValuesEqual] = React.useState(true);

const onSubmit = React.useCallback(values => {
if (!isEqual(originalValues, values)) {
  console.log('submitted.');
  props.handleNext(values);
}
console.log("didn't submit.");}, [props, originalValues]);


useEffect(() => setAreValuesEqual(isEqual(originalValues, formik.values)), [formik.values, originalValues]);


<div>
        <Button
          type="submit"
          variant="contained"
          color="primary"
          className={classes.button}
          data-testid="next"
          disabled={areValuesEqual}
        >
          Next
          </Button>
      </div>

Here is my test:

    describe('FormComponent', () => {
const Spec = {
  appName: 'somerepo',
  repo: 'project-somerepo',
  proxies: [
    {
      env: {
        dev: {
          basepath: '/somerepo-dev.net',
          target: 'https://somerepo-dev.net',
        },
        test: {
          basepath: '/somerepo-test.net',
          target: 'https://somerepo-test.net',
        }
      },
    },
  ],
};

function renderFormComponent() {
  return render(
        <ManageFormComponent metadata={metadata} handleNext={() => { }} />
  );
}

it.only('should render form', async () => {
  await act(async () => {
    renderFormComponent();
    await Promise.resolve();
  });
  expect(screen).toBeDefined();
  expect(screen.getByText('Project Repo')).toBeInTheDocument();
  const Repo = await screen.findByTestId('Repo');
  const RepoInput = Repo.querySelector('input')!;
  RepoInput.focus();
  fireEvent.change(document.activeElement!, {
    target: { value: 'project-somerepo' },
  });
  fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' });
  fireEvent.keyDown(document.activeElement!, { key: 'Enter' });
  expect(await screen.findByText('I want to')).toBeInTheDocument();
  const deploy = await screen.findByTestId('deployment');
  const deployInput = deploy.querySelector('input')!;
  deployInput.focus();
  fireEvent.change(document.activeElement!, {
    target: { value: 'promote service' },
  });
  fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' });
  fireEvent.keyDown(document.activeElement!, { key: 'Enter' });

  expect(
    await screen.findByText('Select an environment to deploy'),
  ).toBeInTheDocument();
  const env = await screen.findByLabelText('TEST');
  userEvent.click(env);

  const Target = await screen.findByText('Target Endpoint')
  expect(Target).toBeInTheDocument();
  expect(await screen.findByTestId('target')).toHaveValue(
    Spec.proxies[0].env.dev.target,
  );

  const Basepath = await screen.findByText('BasePath')
  expect(Basepath).toBeInTheDocument();
  expect(await screen.findByTestId('basepath')).toHaveValue(
    Spec.proxies[0].env.dev.basepath,
  );

  const TargetInput = Target.querySelector('input')
  TargetInput?.focus();
  fireEvent.change(document.activeElement!, {
    target: { value: 'https://somerepo-test.net' }
  })

  const BasepathInput = Basepath.querySelector('input')
  BasepathInput?.focus();
  fireEvent.change(document.activeElement!, {
    target: { value: '/somerepo-test.net' }
  })
  const nextButton = await screen.findByRole('button', { name: /Next/ });
  expect(nextButton).toBeEnabled();
});
}); ```

I get below error, which i believe is happening due to useEffect hook, where I compare the values of fetched values and updated values. If they are not equal, then submit button is enabled. For example below are the JSON objects are being compared:

   expect(element).toBeEnabled()

    Received element is not enabled:
      <button class="MuiButtonBase-root MuiButton-root MuiButton-contained makeStyles-button-6 MuiButton-containedPrimary Mui-disabled Mui-disabled" data-testid="next" disa
bled="" tabindex="-1" type="submit" />

      336 |
      337 |     // expect(nextButton).toBeTruthy();
    > 338 |     expect(nextButton).toBeEnabled();
          |                        ^
      339 |   });
0

There are 0 answers