testing-library/react-hooks-testing-library

result.all is null - how can I test the initial value set in a hook before a useEffect kicks in?

Closed this issue · 1 comments

  • react-hooks-testing-library version: ??
  • react version: 19
  • react-dom version: 19
  • node version: 20
"dependencies": {
    "babel-jest": "^29.7.0",
    "next": "15.1.3",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "ts-jest": "^29.2.5"
  },
  "devDependencies": {
    "@babel/preset-env": "^7.26.0",
    "@testing-library/dom": "^10.4.0",
    "@testing-library/react": "^16.1.0",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0"
  }

Relevant code or config:

  • useHook.js
import { useEffect, useState } from 'react';

const useHook = () => {
    const [value, setValue] = useState('default');

    useEffect(() => {
        setValue(31337);
    }, []);
     //throw new Error(value); // logs 'default' - how can I test this?
    return value;
};

export default useHook;
  • useHook.test.js
import { renderHook } from '@testing-library/react';
import useHook from "./useHook";

describe('useHook', () => {
    it('should return 31337', () => {

        // Act
        const { result } = renderHook(() => useHook());

        // Assert
        expect(result.all[0]).toBe('default'); // fails, all doesn't exist for some reason
        expect(result.current).toBe(31337);
    });
});

What you did:

Hi folks, I'm trying to test a hook that causes a bug for us. I can fix the bug by changing the initial useState call but I really want to add a test to stop this regressing.

I can't get it to test the return value of 'default' at all. result.all is undefined, the only thing I see is result.current, which is 31337 - but if I uncomment the throw you can see that it does return 'default' at first.

How can I test this please?

I looked at #716 which looks like the same bug, but the solution there doesn't apply because I can't see the .all property.

I think I'm using a different library, but it is a shame because the .all functionality is exactly what I needed.