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.useFakeTimers are not working after update to version 8

See original GitHub issue
  • @testing-library/dom version: 8.1.0
  • Testing Framework and version: jest 26.6.0
  • DOM Environment: jsdom 16.4.0

Relevant code or config:

const App = () => {
  const [count, setCount] = useState(0)

  useEffect(() => {
    let isSubscribed = true
    let timeoutId: NodeJS.Timeout

    const updateCount = async () => {
      try {
        const response = await fetch('index.html')
        const content = await response.text()
        
        if (isSubscribed) {
          console.log(content)
          setCount(prev => prev + 1)
        } 
      }catch (err) {
        console.error(err)
      }

      timeoutId = setTimeout(updateCount, 10000)
    }

    updateCount()

    return () => {
      isSubscribed = false
      clearTimeout(timeoutId)
    }
  }, [])

  return (
    <div>
      Count: {count}
    </div>
  );
}
it('should display name', async () => {
  jest.useFakeTimers()

  const mockText = jest.fn()
  mockFetch.mockImplementation(() => Promise.resolve({ text: mockText }))
  mockText.mockReturnValue(Promise.resolve('1.0.0'))

  render(<App />);
  
  expect(mockFetch).toHaveBeenCalledTimes(1)

  act(() => {
    jest.runOnlyPendingTimers()
  })

  await waitFor(() => {
    expect(mockFetch).toHaveBeenCalledTimes(2 )
  })
});

What you did:

Updating @testing-library/react from 11.2.7 to 12.0.0 which updates @testing-library/dom from 7.31.2 to 8.1.0

What happened:

Test with using jest.useFakeTimers() were failing

Reproduction:

GitHub-Repo: https://github.com/netcoding87/fake-timers

Clone repo. => Branch master is working with @testing-library/dom 7.31.2 => Test is passing => Branch update-testing-lib with @testing-library/dom 8.1.0 => Test is failing

Problem description:

I read the recommendations for release 8.0.0 but using modern timers did also not work.

Suggested solution:

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
eps1loncommented, Sep 10, 2021

This looks like it’s just a timeout issue. Everything is passing with

  await waitFor(() => {
    expect(mockFetch).toHaveBeenCalledTimes(2 )
  }, { timeout: 11000 }

Looks like it’s running a bit slower in fake timers now.

Will keep an eye on it but for now this seems minor enough to ignore i.e. just recommend increasing the timeout.

0reactions
adnan-sheikhcommented, Feb 17, 2022

I am experiencing somewhat similar issue. I am on CRA setup and I upgraded react-scripts to 5.0.0.

Previously I was on: “@testing-library/jest-dom”: “^5.11.4”, “@testing-library/react”: “^11.1.0”,

and then I upgraded to: “@testing-library/jest-dom”: “^5.16.1”, “@testing-library/react”: “^12.1.2”,

but now my tests are failing,

beforeEach(() => {
  jest.useFakeTimers()
}

afterEach(() => {
  jest.useRealTimers()
}
.
.
.
render(<Component />);
await waitForElementToBeRemoved(() => screen.queryByTestId("loader"));
//   ^? Test is failing here "waitFor... getting timedout"

before upgrading it was passing I’m using MSW for mocking.

If i’m not using fake timers, test passes But, I need fake timers to skip setTimeout on a notification component, as I am waiting for it to be removed at the end of test. Any help?

Read more comments on GitHub >

github_iconTop Results From Across the Web

useFakeTimers not working in jest/testing-library
You should advance timers after rendering the component. Besides, you should call jest.advanceTimersByTime() inside act function.
Read more >
Timer Mocks - Jest
In the following example we enable fake timers by calling jest.useFakeTimers() . ... runOnlyPendingTimers() will solve the problem:.
Read more >
Using Fake Timers | Testing Library
To solve these problems, or if you need to rely on specific timestamps in your code, ... jest.useFakeTimers() }). When using fake timers, ......
Read more >
Mock JavaScript Dates with Fake Timer and Jest
But since then, JS evolved a lot and today, Date JS objects are ... it('Should work', () => { jest.useFakeTimers(); const date =...
Read more >
Jest TypeError: Cannot read property 'useFakeTimers' of ...
run a unit test under packages/nodes-base got failed. But I can fix it by remove node_models and reinstall again with npm install ......
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