Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Change a state value in React Testing Library

Having the following component:

import { useState } from 'react';

export function MyComponent() {
  const [val, setVal] = useState(false);

  return (
    <div>
      big container
      <button onClick={() => setVal(!val)}>click</button>
      {val && <div>small container</div>}
    </div>
  );
}

export default MyComponent;

There is a div containing the text "small container", which only appears when val is true.

I want to write a test in jest for this but don't know how to mock the value of val there

Here is my code so far:

  it('small container visible only when val is true', () => {
    const { queryByText } = render(<MyComponent />);
    const toTest = queryByText('small container');
    expect(toTest).not.toBeInTheDocument();
  });

this test passes, but how can be added val set to true in order to test that toTest is present in the document?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can click the button which will set the val to true.

it('small container visible only when val is true', () => {
  const {queryByText, getByTestId} = render(<MyComponent />);
  const clickButton = getByTestId('your.button.test.id');
  fireEvent.click(clickButton);
  expect(queryByText('small container')).toBeInDocument();
});

React testing library does not recommend to test implementation details as per documented here. That's why you might not want to access internal state of component while testing.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!