Search code examples
typescriptjestjses6-proxy

undefined returned when using identity-obj-proxy with typescript with jest


I am using jest with typescript in my projects. I am getting undefined for all my .ts files using identity-obj-proxy but .js files work as expected.

This is my tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "outDir": "lib",
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules/@microsoft"
    ],
    "types": [
      "es6-promise",
      "webpack-env"
    ],
    "lib": [
      "es5",
      "dom",
      "es2015.collection"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "lib"
  ]
}

This is my jest configuration:

"jest": {
    "unmockedModulePathPatterns": [
      "React"
    ],
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "^.+\\.(d\\.ts|ts|tsx)$": "ts-jest"
    },
    "testMatch": [
      "**/src/**/*.test.+(ts|tsx|js)"
    ],
    "setupFiles": [
      "raf/polyfill"
    ],
    "collectCoverage": true,
    "coverageReporters": [
      "json",
      "lcov",
      "text",
      "cobertura"
    ],
    "coverageDirectory": "<rootDir>/jest",
    "collectCoverageFrom": [
      "**/*.{ts,tsx}",
      "!**/*.d.{ts,tsx}",
      "!**/*.scss.ts",
      "!**/models/**",
      "!**/node_modules*/**"
      "!**/services/http.ts"
    ],
    "moduleNameMapper": {
      "\\.(css|less|scss|sass)$": "identity-obj-proxy",
      "^resx-strings/en-us.json": "<rootDir>/node_modules/@microsoft/sp-core-library/lib/resx-strings/en-us.json"
   },
    "reporters": [
      "default",
      "jest-junit"
    ],
    "coverageThreshold": {
      "global": {
        "branches": 50,
        "functions": 75,
        "lines": 75,
        "statements": 75
      }
    }
  }

My test file(.ts):

import styles from './Somefile.module.scss';

describe('Test identity proxy', () => {
  test('undefined returned', () => {
    expect(styles.notundefined).toBe(undefined);
  }
});

If I save the file as .js then everything seems to work but not in .ts or .tsx files.


Solution

  • Try importing your scss file as

    import * as styles from './Somefile.module.scss';
    

    There's an issue with identity-obj-proxy that prevents the standard import syntax from working in TypeScript, but for some reason the import * as notation works fine.

    https://github.com/keyanzhang/identity-obj-proxy/issues/8