How to correctly mock the library "Twemoji" when running unit tests in angular + jest?

231 Views Asked by At

My objective is to run unit tests in my Angular application with jest, without getting:

error TS2304: Cannot find name 'twemoji'

Twemoji is added to the projects package.json and the angular.json file, scripts section. It works perfectly when running and building the application, but fails with the above error when running unit tests.

What I have tried

I have tried adding the following to my src/jestGlobalMocks.ts file:

declare var twemoji: {
    parse(str: string, options?: { folder: string; ext: string }): string;
};
Object.defineProperty(window, 'twemoji', {
    value: {
        parse: str => str,
    },
});

and src/typings.d.ts:

declare var twemoji: {
    parse(str: string, options?: { folder: string; ext: string }): string;
};

But this does not seem to solve the problem, as I still get error TS2304. I seem to get some inconsistent behavior, as it seems to work sometimes? Looking forward to a solution/explanation :)

1

There are 1 best solutions below

3
On BEST ANSWER

Thoughts:

  1. try to install types for twemoji
  2. basically src/typings.d.ts should work. Does it included to the compilation process? Is it listed in your tests tsconfig files or include section? You can check it running tsc --project=tsconfig.spec.json --outDir=output --listFiles
  3. try to change code in typings.d.ts to this:
    declare module 'twemoji' {
      export function parse(str: string, options?: { folder: string; ext: string }): string;
    }