Jest with Angular: Add *.extension.ts file to extend array methods

Viewed 21

I have write a Typescript extension write for Angular and include the extension via main.ts:

import 'src/app/shared/extensions/array.extension';

Thats works fine, but the unitests in Jest get the error 'TypeError: dataItems.filter(...).sortByStatusName is not a function'.

Whats wrong? My tsconfig.spec.json looks like:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "target": "ESNext",
    "module": "commonjs"
  },
  "files": [
    "src/polyfills.ts",
    "src/setup-jest.ts"
  ],
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts",
    "src/**/test/*.data.ts",
    "**/*.extension.ts"
  ]
}

and my jest.config.js

const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig.json');


// https://thymikee.github.io/jest-preset-angular/docs/guides/angular-13+
// https://jestjs.io/docs/ecmascript-modules


// to start jest in ES module mode:
// 1. add "type": "module",   to package.json
// 2. start with: yarn test-esm

module.exports = {
  preset: 'jest-preset-angular',
  maxConcurrency: 1,
  testEnvironment: 'jsdom',
  globalSetup: 'jest-preset-angular/global-setup',
  setupFilesAfterEnv: [
    '<rootDir>/src/setup-jest.ts',
    'jest-canvas-mock',
  ],

  roots: [
    '<rootDir>/src/app'
  ],
  moduleNameMapper: {
    ...pathsToModuleNameMapper(compilerOptions.paths, {prefix: '<rootDir>/'}),
    'src/app/app-mode.service': '<rootDir>/src/app/app-mode.service',
  },

  testMatch: [
    '**/+(*.)+(spec).+(ts|js)'
  ],

  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment',
  ],

  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.html$'
    }
  },

  collectCoverage: false,
  collectCoverageFrom: [
    '**/src/**/*.ts',
    '!test/**',
    '!tests/**',
    '!**/test/**',
    '!**/tests/**',
    '!**/__test__/**',
    '!**/__tests__/**',
    '!**/polyfills.ts',
    '!**/environments/**',
    '!**/src/setup-jest.ts',
    '!**/node_modules/**',
    '!**/src/**/*.module.ts',
  ],
  coverageReporters: ['html', 'text','lcov'],
  coverageDirectory: 'coverage',
};

Have you a solution for this?

0 Answers
Related