4

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

skyboyer
  • 22,209
  • 7
  • 57
  • 64
DauleDK
  • 3,313
  • 11
  • 55
  • 98

1 Answers1

2

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;
    }
nickbullock
  • 6,424
  • 9
  • 27
  • 1
    Tried point 3 with no success. But installing the types did it for me. Thanks @nickbullock. – Manish Shrestha Nov 28 '19 at 13:27
  • So in an Angular CLI setup, where should the `typings.d.ts` file be inlcuded? Is it not included because the `tsconfig.app.json` has an `files` entry with `.`, and the `tsconfig.spec.json` extands the `tsconfig.app.json`? – DauleDK Nov 29 '19 at 12:12
  • @DauleDK in ng new project i can see that `tsconfig.spec.json` extends `tsconfig.json` and has option "include": [ "src/**/*.spec.ts", "src/**/*.d.ts" ], so your typings.d.ts will be included by `src/**/*.d.ts` rule – nickbullock Nov 29 '19 at 13:16