testing-library / react-hooks-testing-library

🐏 Simple and complete React hooks testing utilities that encourage good testing practices.
https://react-hooks-testing-library.com
MIT License
5.25k stars 230 forks source link

`restoreConsole` is not a function error if a test fails `beforeEach()` #959

Closed dieseldjango closed 1 year ago

dieseldjango commented 1 year ago

Relevant code or config:

In core/console.js:

function enableErrorOutputSuppression() {
  // Automatically registers console error suppression and restoration in supported testing frameworks
  if (
    typeof beforeEach === 'function' &&
    typeof afterEach === 'function' &&
    !errorFilteringDisabled()
  ) {
    let restoreConsole!: () => void

    beforeEach(() => {
      restoreConsole = suppressErrorOutput()
    })

    afterEach(() => restoreConsole())
  }
}

What you did:

Wrote a test with a beforeEach() that throws an error.

What happened:

TypeError: restoreConsole is not a function

      at Object.<anonymous> (node_modules/@testing-library/react-hooks/lib/core/console.js:45:21)

Reproduction:

Don't have this yet, I can create if necessary, but I think the fix is pretty simple.

Problem description:

I'm using jest 27.5.1, and apparently the way it works, if my test throws an error in its beforeEach(), your beforeEach() that is setup in enableErrorOutputSuppression() is not called. However, your afterEach() is still called, and throws an error because restoreConsole() is undefined.

Suggested solution:

    afterEach(() => {
      if (restoreConsole) {
        restoreConsole()
      })
mpeyper commented 1 year ago

Thanks for raising this issue.

If you feel strongly about it, please feel free to raise a PR to fix it (I think your suggestion here is fine, or even just setting a noop default value for restoreConsole so it is always defined), but in general this library should be considered somewhat deprecated now and folks should be migrating across to testing-library/react instead (where they do not hijack the console output like we do).

dieseldjango commented 1 year ago

Given the status of the library and that the error only happens if beforeEach() throws an error anyway, I don't think this is worth fixing.