Skip to content

Testing useEffect callback #289

Closed
Closed
@Andrewmat

Description

@Andrewmat

Describe the feature you'd like:

I've had this problem on a personal project to try and create custom hooks.

The useEffect hook accepts a function as argument, and if this function returns another function, React will call it when the component unmounts

useEffect(() => {
  subscribe(channel)
  return () => {
    // componentWillUnmount
    unsubscribe(channel)
  }
})

The testHook API already can test the useEffect call, but I couldn't find a way to test the callback on unmount.

Suggested implementation:

The testHook function renders a wrapper component and already has access to the unmount function. My suggestion is to simply return it inside an object.

function testHook(callback) {
  const { unmount } = render(<TestHook callback={callback} />)
  return { unmount }
}

This is simple to do, and I think it is clear too. Also it can be expand to other important return values when needed.

Describe alternatives you've considered:

My first thought was to return the unmount function alone

function testHook(callback) {
  const { unmount } = render(<TestHook callback={callback} />)
  return unmount
}

I did this to mimic the behavior of the useEffect. However, it didn't look good to me, as it would get all the usage of testHook return.

Teachability, Documentation, Adoption, Migration Strategy:

I've took the liberty to create a fork containing my sugestion.
https://github.com/Andrewmat/react-testing-library

Plus tests and a example

I've already tested in my personal project using yarn link and it worked.

captura de tela de 2019-02-08 21-38-14

If this feature is considered, I'd be glad to make a pull request of it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions