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

Having trouble testing useEffect/useState in hook #114

Closed
epignosisx opened this issue Jul 12, 2019 · 3 comments
Closed

Having trouble testing useEffect/useState in hook #114

epignosisx opened this issue Jul 12, 2019 · 3 comments
Labels
question Further information is requested

Comments

@epignosisx
Copy link

I'm having trouble making the following test pass and I was hoping you can help me.

import { useEffect, useState } from "react";

export function useComponentResources(required) {
  const [componentResources, setComponentResources] = useState(null);

  useEffect(() => {
    if (required) {
      // api call
      setTimeout(() => setComponentResources({}), 100);
    }
  }, [required]);

  return componentResources;
}
import { renderHook } from "@testing-library/react-hooks";
import { useComponentResources } from "./component-resources.hook";

describe("component-resources.hook", () => {
  it("fetches resources when required", () => {
    //act
    const { result } = renderHook(() => useComponentResources(true));

    //assert
    expect(result.current).toEqual({});
  });
});

It keeps failing:

expect(received).toEqual(expected)

Expected value to equal:
  {}
Received:
  null

Difference:

  Comparing two different types of values. Expected object but received null.

   7 |     const { result } = renderHook(() => useComponentResources(true));
   9 |     //assert
> 10 |     expect(result.current).toEqual({});
  11 |   });
  12 | });

I have created a repro case in codesandbox. Hopefully it makes it easier point out what I'm doing wrong:

https://codesandbox.io/embed/priceless-browser-94ec2

@epignosisx epignosisx added the question Further information is requested label Jul 12, 2019
@mpeyper
Copy link
Member

mpeyper commented Jul 12, 2019

I can't take a closer look right now, but it sounds like the same issue as #102. Let me know if that doesn't cover it.

@mpeyper
Copy link
Member

mpeyper commented Jul 12, 2019

Actually, the timeout means it's different... You want to use waitForNextUpdate (docs).

@epignosisx
Copy link
Author

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants