Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
user24 opened this issue Jan 6, 2025 · 1 comment
Labels
bug Something isn't working

Comments

@user24
Copy link

user24 commented Jan 6, 2025

  • 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.

@user24 user24 added the bug Something isn't working label Jan 6, 2025
@user24
Copy link
Author

user24 commented Jan 16, 2025

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

@user24 user24 closed this as completed Jan 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant