Jest: TypeError: Cannot read property 'foo' of undefined

Viewed 1657

I am creating new QA issue to share my findings as I have got same error as discussed already in SO but my problem was elsewhere. Reference: Jest: TypeError: Cannot read property of undefined

I was getting error "TypeError: Cannot read property 'apiUrl' of undefined". I could not find out why. I had already set esModuleInterop and allowSyntheticDefaultImports tsconfig.json so I thought all export types are supported.

Error occurs in service consumer

import Axios from 'axios';
import config from '@/services/config.service';

const axios = Axios.create({
  baseURL: config.apiUrl || undefined,
                  ^^^^^^
  ...
});

where config services exported const config and even as default export too

export let config: AppConfig;

...

config = {...}

...

export default config;

my tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": ["node", "webpack-env", "jest", "googlemaps"],
    "paths": {
      "@/*": ["src/*"],
    },
    "lib": ["esnext", "dom", "dom.iterable", "scripthost"],
    "skipLibCheck": true
  },
  "include": [
    "src/main.ts",
    "src/types/**/*",
    "src/WS_UIkit/src/types/**/*"
  ],
  "exclude": ["node_modules"]
}

my jest.config.js

module.exports = {
  preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
  // testMatch: ['**/*.spec.[jt]s?(x)],'
  testMatch: ['**/*.spec.ts'],
  moduleNameMapper: {
    // FIXES Could not locate module @/types mapped as: .../cart/src/types.
    '^@/types$': '<rootDir>/src/types/index.d',
  },
  transformIgnorePatterns: ['node_modules/(?!(quasar|quasar/*))'],
};

my babel config

module.exports = {
  presets: ['@vue/app'],
  plugins: [
    [
      'transform-imports',
      {
        quasar: {
          transform: 'quasar/dist/babel-transforms/imports.js',
          preventFullImport: true,
        },
      },
    ],
  ],
};
1 Answers

My problem was that I have exported uninitialised constant export let config: AppConfig; and then, later on, initialised it config = {...} therefore in time of export it is undefined. But it is a mystery to me why it works in app without error, maybe it executes code and then resolves exports? And jest does the opposite? Why it is different? Isn't the same ts compiler used? At least the issue is solved for me.

Related