question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Jest Testing with use-between hooks

See original GitHub issue

Anyone Jest testing with use-between hooks? Let me give you a shortened example code…

export const MyDialog = () => {

   // shared use between hook set in another component
   const { displayAddAnalysis, setDisplayAddAnalysis } = useMyHook();

    return (
        <Dialog id="dlg-new-planned-analysis" 
                      header={`New Planned Analysis`} 
                      visible={displayAddAnalysis} 
                       onHide={onHide}>
    )
}

I need to set the displayAddAnalysis use-between hook value to true for my Jest test.

Here is the only way we could figure out to set it because use-between must be used in a Component is to create a fake <testComponent> but some on our dev team think this feels wrong. Any thoughts on the best way to test use-between hooks in Jest?

function getDialog() {
    //Test component exists so that the setMyHook can be switched to true.
    //Otherwise, the Dialog component will not exist to test
    function TestComponent() {
        const { setDisplayAddAnalysis } = usePlannedAnalysisHook();
        setDisplayAddAnalysis(true);
        return null;
    }
    render(<TestComponent />);
    return render(<MyDialog />);
}

test("Making sure error messages do not show on component loading", async () => {
    //Arrange
    const Dialog = getDialog();

    // Act
    const study = await Dialog.findByTestId("studyError");

    //Assert
    expect(study.textContent).toMatch("");
});

}

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
mellowarecommented, Feb 7, 2022

@betula We confirmed these changes now make it all work perfectly. You are awesome!

2reactions
betulacommented, Feb 7, 2022

Hello @Abielf!

Okay. With the “act” questions arose, I removed it from “use-between” (1.2.1).

Now we need to use “act” from “@testing-library/react” only where we need it. The “act” is exactly what is needed in those places where the warnings “was not wrapped in act(...)” appear.

There is no additional “act” for “use-between” operations anymore.

import { get, useBetween, clear, mock } from 'use-between'
import { act, render } from '@testing-library/react'
afterEach(clear)
it('It works', async () => {
  expect(get(useCounter).count).toBe(0)

  // Without act
  get(useCounter).inc()

  // Check result
  expect(get(useCounter).count).toBe(1)

  get(useCounter).inc()
  expect(get(useCounter).count).toBe(2)
})
it('It works with testing-library render component', async () => {
  const Counter = () => {
    const { count } = useBetween(useCounter)
    return <i data-testid="count">{count}</i>
  }

  const el = render(<Counter />)
  expect((await el.findByTestId('count')).textContent).toBe('0')

  // You should use "act" from @testing-library/react
  // otherwise there will be a warning.
  act(() => {
    get(useCounter).dec()
  })
  expect((await el.findByTestId('count')).textContent).toBe('-1')
})

I also have great news! I made a “mock” function for you!

it('It works with testing-library render component with mock', async () => {
  mock(useCounter, { count: 10 })

  const el = render(<Counter />)
  expect((await el.findByTestId('count')).textContent).toBe('10')

  // You should use "act" from @testing-library/react
  // otherwise there will be a warning.
  // Because here we are updating the state of the mock.
  act(() => {
    mock(useCounter, { count: 15 })
  })
  expect((await el.findByTestId('count')).textContent).toBe('15')
})

Try It Out and Happy Coding!

Read more comments on GitHub >

github_iconTop Results From Across the Web

A Complete Guide to Testing React Hooks - Toptal
This article explores how to test React Hooks and outlines an eight-step testing ... Test Utilities and Jest) and then by using react-hooks-testing-library....
Read more >
Testing React: Components, Containers and Custom Hooks.
This tutorial is aimed at the testing of a Parcel + React application, built using thefrontend/contextStore and custom hooks.
Read more >
betula/use-between: Sharing state between React components
useBetween is a way to call any hook. But so that the state will not be stored in the React component. For the...
Read more >
How to test React Hooks - LogRocket Blog
The goal of this article is to provide a practical guide on testing React Hooks using tools such as React Testing Library, Jest,...
Read more >
React hooks (v17.0.3) and Redux handbook using TypeScript ...
Note - Avoid the open source custom hook called useBetween since it ... npm install --save @testing-library/react @testing-library/jest-dom.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found