testing-library/react-hooks-testing-library

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

dieseldjango opened this issue · 2 comments

  • react-hooks-testing-library version: 7.0.2 (but code is same in main branch)
  • react version: 17.0.1
  • node version: 18.14.0
  • yarn version: 1.22.19

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()
      })

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).

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.