1 year ago

#356269

test-img

amsub24

Unable to test combination of useEffect and setTimeout using Jest

Trying to assert a simple state change made using useEffect and setTimeout. The effect calls setTimeout with a value of 1500ms which should change the displayed string from 'unchanged' to 'changed'.

component

import * as React from 'React';
import {useEffect} from 'React';
import {Text, View} from 'react-native';

export function Dummy() {
  const [str, changeStr] = React.useState('unchanged');

  useEffect(() => {
    setTimeout(() => {
      changeStr('changed');
    }, 1500);
  }, []);

  return (
    <View>
      <Text>{str}</Text>
    </View>
  );
}

test

import {render, waitFor} from '@testing-library/react-native';
import * as React from 'React';
import {Dummy} from '../Dummy';

// Activate fake timers
jest.useFakeTimers();

describe('Dummy', () => {
  it('should change the string after 1500 ms', async () => {
    const {getByText} = render(<Dummy />);

    // run all timers which should fire the state update
    jest.runAllTimers();

    await waitFor(
      () => {
        expect(getByText('changed')).toBeTruthy();
      },
      {timeout: 5000},
    );
  });
});

result

 FAIL  src/components/__tests__/dummy.spec.js (8.037 s)
  Dummy
    ✕ should change the string after 1500 ms (5226 ms)

  ● Dummy › should change the string after 1500 ms

    : Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

       7 |
       8 | describe('Dummy', () => {
    >  9 |   it('should change the string after 1500 ms', async () => {
         |   ^
      10 |     const {getByText} = render(<Dummy />);
      11 |
      12 |     // run all timers which should fire the state update

      at new Spec (node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
      at Suite.<anonymous> (src/components/__tests__/dummy.spec.js:9:3)

anyone know why this is and how I can successfully test this?

reactjs

react-native

react-hooks

jestjs

react-native-testing-library

0 Answers

Your Answer

Accepted video resources