Trinu
Trinu

Reputation: 1761

React 18 useState not updating the state after promise call in test cases

This is simple App.jsx

import React, { useState } from 'react';

const App = () => {
  const [showDialogue, setShowDialogue] = useState(false);

  const handleButtonClick = async () => {
    setShowDialogue((prev) => {
      console.log('inside before api call', prev); // This is printing
      return false;
    });  
    console.log('Button clicked, making API call...');
    try {
      // Simulate API call
      const response = await new Promise(resolve => {
        setTimeout(() => resolve({ success: true }), 1000);
      });
      console.log('API success', response);

      setShowDialogue((prev) => {
        console.log('inside after', prev);
        return true;
      });  // Ensure the state is updated here
    } catch (error) {
      console.log('API call failed', error);
    }
  };

  console.log('showdialogue', showDialogue);  //this is always false not updating

  return (
      <div className="App">
        <header className="App-header">
          <h1>React Test Case Example</h1>
          <button onClick={handleButtonClick}>Trigger API Call</button>
          {showDialogue && <p>The dialogue is now open!</p>}
        </header>
      </div>
  );
};

export default App;

This is my App.test.js

 import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { act } from 'react';  // Correct import for React 18
import App from './App';

test('displays dialogue text after API call success', async () => {
  render(<App />);

  // Ensure initial state: dialogue text should not be in the document initially
  expect(screen.queryByText('The dialogue is now open!')).toBeNull();

  const button = screen.getByText('Trigger API Call');

  // Use act to simulate an async event
  await act(async () => {
    fireEvent.click(button);
  });

  // Wait for the state update to reflect in the DOM
  await waitFor(() => {
    expect(screen.getByText('The dialogue is now open!')).toBeInTheDocument();
  });
});

The test case is failing when i debug the state is not updating via test cases. Any help on this how to fix. I am using depdendencies

 "dependencies": {
    "@testing-library/jest-dom": "^6.6.3",
    "@testing-library/react": "^13.4.0",
    "cra-template": "1.2.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1"
  },

Upvotes: 0

Views: 26

Answers (0)

Related Questions