ValentinH / jest-fail-on-console

Utility to make jest tests fail when console.error() or any other methods are used
MIT License
146 stars 21 forks source link

Typescript export type is incorrect #7

Closed amakhrov closed 2 years ago

amakhrov commented 2 years ago

It currently says export default init. This doesn't match the actual .js code, which uses module.exports = init pattern. As a result, it's not possible in a .ts file to correctly import and use the jest-fail-on-console module, without having a type assertion (as any).

A proper TS annotation for that would look like

export = init;

And then a consumer would import it like that:

import * as failOnConsole from 'jest-fail-on-console'

Docs: https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require

Full `.d.ts` ```typescript declare namespace init { type InitOptions = { /** * This function is called for every console warn/error. * If true is returned, the message will not show in the console * and the test won't fail. */ silenceMessage?: (message: string, methodName: 'warn' | 'error' | 'log') => boolean /** defaults to true */ shouldFailOnWarn?: boolean /** defaults to true */ shouldFailOnError?: boolean /** defaults to false */ shouldFailOnLog?: boolean } } declare function init(options?: init.InitOptions): void export = init ```

Thanks!

ValentinH commented 2 years ago

I'm currently using this library in a TS project and it works fine. Here's how I'm using it:

import failOnConsole from 'jest-fail-on-console'

failOnConsole({
  silenceMessage: (message) => {
    // this is a limitation of jsdom that prevent us from clicking anchor link in tests https://github.com/jsdom/jsdom/issues/2112#issuecomment-359297866
    if (message.includes('Not implemented: navigation')) {
      return true
    }
    return false
  },
})

How are you using it?

amakhrov commented 2 years ago

This compiles but errors at run time, because the library doesn't have a default export Screen Shot 2021-10-18 at 9 53 49 AM

Our Angular app uses tsc to compile the code. If you use Babel, you can get different results if babel does some magic behind the scenes (like, generates a synthetic default export).

amakhrov commented 2 years ago

So basically there are 2 problems here: compile-time typechecks and runtime behavior.

One could make the code above work at runtime by enabling esModuleInterop TS compiler setting (disabled by default).

But the typechecking problem is that .d.ts doesn't match the actual underlying .js file - because module.exports = init (.js) is not the same as export default init (.d.ts).

ValentinH commented 2 years ago

@amakhrov could you please have a look to #8 to confirm that this is what you need?

ValentinH commented 2 years ago

This should be fixed in v2.1.1