nuxt-community / composition-api

Composition API hooks for Nuxt 2.
https://composition-api.nuxtjs.org
MIT License
709 stars 101 forks source link

fix: Cannot use import statement outside a module #671

Closed theolavaux closed 2 years ago

theolavaux commented 2 years ago

šŸ› The bug Since I upgraded to 0.33.0, my tests are not passing anymore because it seems like Jest is pointing to the wrong file. node_modules/@nuxtjs/composition-api/dist/runtime/index.mjs instead of node_modules/@nuxtjs/composition-api/dist/runtime/index.js

Full output

 FAIL   bddf-bodyguard  my-project/test/integration/components/MyComponentTest.test.ts
  ā— Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     ā€¢ If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     ā€¢ If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     ā€¢ To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     ā€¢ If you need a custom transformation specify a "transform" option in your config.
     ā€¢ If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /my-project/node_modules/.pnpm/@nuxtjs+composition-api@0.33.0_ndg5g6d2rkyeqt4q3tlrv66tjm/node_modules/@nuxtjs/composition-api/dist/runtime/index.mjs:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { getCurrentInstance as getCurrentInstance$1, ref, customRef, shallowRef, onServerPrefetch, isRef, reactive, toRefs, watch, computed, isReactive, toRaw, onBeforeMount, set } from 'vue';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    [...]

      at Runtime.createScriptFromCode (../../node_modules/.pnpm/jest-runtime@28.1.3/node_modules/jest-runtime/build/index.js:1796:14)
      at Object.<anonymous> (components/MyComponent.vue:9:27)
      at Object.<anonymous> (test/integration/components/MyComponentTest.test.ts:6:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        8.58 s
Ran all test suites.

šŸ› ļø To reproduce Steps to reproduce the behavior:

  1. Create a new Nuxt 2 project
  2. Configure Jest
  3. Install @nuxtjs/composition-api@0.33.0
  4. Try to launch your tests

Repro here: https://stackblitz.com/edit/nuxt-starter-btq2rq?file=jest.config.ts

šŸŒˆ Expected behaviour Tests pass

danielroe commented 2 years ago

You can add an alias in your jest config:

import { join } from 'path';

module.exports = {
  moduleNameMapper: {
    '^@nuxtjs/composition-api$': join(
      __dirname,
      'node_modules/@nuxtjs/composition-api/dist/runtime/index.js'
    ),
  },
}
theolavaux commented 2 years ago

This is what I get

 FAIL   my-project my-project/test/integration/components/MyComponentTest.test.ts
  ā— Test suite failed to run

    Configuration error:

    Could not locate module @nuxtjs/composition-api mapped as:
    /Users/theolavaux/projects/my-project/node_modules/@nuxtjs/composition-api/dist/runtime/index.js.

    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^@nuxtjs\/composition-api$/": "/Users/theolavaux/projects/my-project/node_modules/@nuxtjs/composition-api/dist/runtime/index.js"
      },
      "resolver": /Users/theolavaux/projects/my-project/test/integration/resolver.js
danielroe commented 2 years ago

Well, you may need to confirm the exact path in your repo setup.

theolavaux commented 2 years ago

Whoops yeah, I'm working on an Nx repo and I forgot that my node_modules is not directly located in the project itself, it works now, thanks, you rock šŸŽø

dvoulety commented 2 years ago

Hi @danielroe, after updating to 0.33.1, I got also error SyntaxError: Cannot use import statement outside a module. So I added node_modules/@nuxtjs/composition-api/dist/runtime/index.js to jest.config.js. But now I get this error:

const vue_1 = require("vue");
          ^

    SyntaxError: Identifier 'vue_1' has already been declared

      17 | import { defineAsyncComponent, computed, watch, onMounted } from 'vue'
      18 | import { useContext, useRoute, useAsync } from '@nuxtjs/composition-api'
    > 19 | import SearchResults from '@/components/SearchResults.vue'
         | ^

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1678:14)
      at Object.<anonymous> (src/components/SearchRequest.vue:19:1)
      at Object.<anonymous> (tests/setupEnv.js:8:1)

Any idea?

My jest.config.js

module.exports = {
  testEnvironment: 'jsdom',
  testEnvironmentOptions: {
    url: 'http://localhost/',
  },
  moduleFileExtensions: [
    'ts',
    'js',
    'vue',
  ],
  moduleNameMapper: {
    '^@/(.*\\.svg)': '<rootDir>/src/$1',
    '^@/(.*)$': '<rootDir>/src/$1',
    '^@@/(.*)$': '<rootDir>/$1',
    '(@visable-dev.*\\.svg)\\?': '$1',
    '^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^pinia$': 'pinia/dist/pinia.cjs',
    '^@nuxtjs/composition-api$': '<rootDir>/node_modules/@nuxtjs/composition-api/dist/runtime/index.js',
  },
  transform: {
    '^.+\\.(ts)$': 'ts-jest',
    '^.+\\.svg': '<rootDir>/tests/support/svgTransform.js',
    '^.+\\.vue$': '@vue/vue2-jest',
    '^.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.json': '<rootDir>/tests/support/jsonTransform.js',
    '.+': 'babel-jest',
  },
  testMatch: [
    '**/tests/**/*.spec.(js|ts)',
  ],
  setupFiles: [
    './tests/setup.js',
  ],
  setupFilesAfterEnv: [
    './tests/setupEnv.js',
  ],
}

my package.json

{
  "name": "unified-search-frontend",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "generate": "nuxt generate",
    "start": "nuxt start",
    "test": "jest -c jest.config.js",
    "cypress": "cypress run",
    "lint": "yarn lint:js && yarn lint:css",
    "typecheck": "vue-tsc --noEmit --skipLibCheck --project tsconfig.json && vue-tsc --noEmit --skipLibCheck --project cypress/tsconfig.json",
    "lint:js": "eslint --fix --ext ts,js,vue src tests *.js *.ts",
    "lint:css": "stylelint --fix \"**/*.css\" \"**/*.scss\" \"**/*.vue\" \"!**/dist/**\""
  },
  "dependencies": {
    "@intlify/vue-i18n-loader": "^1.0.0",
    "@koumoul/nuxt-config-inject": ">=0.4.12",
    "@maxmind/geoip2-node": ">=3.4.0",
    "@nuxtjs/composition-api": "^0.33.1",
    "@pinia/nuxt": "0.2.1",
    "@popperjs/core": "^2.11.6",
    "@sentry/browser": ">=7.8.0",
    "@sentry/integrations": ">=7.8.0",
    "@sentry/node": ">=7.8.0",
    "axios": ">=0.27.2",
    "body-scroll-lock": ">=3.1.5",
    "cookie-universal-nuxt": "^2.2.1",
    "dd-trace": ">=2.12.1",
    "fuse.js": ">=6.6.2",
    "http-proxy-middleware": ">=2.0.6",
    "ipaddr.js": ">=2.0.0",
    "maplibre-gl": "^2.1.9",
    "morgan": ">=1.10.0",
    "nuxt": "^2.15.8",
    "pinia": "^2.0.22",
    "portal-vue": ">=2.1.7",
    "routing-pattern": ">=1.0.4",
    "throttle-debounce": ">=5.0.0",
    "tracking": ">=1.1.3",
    "vue-i18n": "^8.27.2",
    "vue-lazy-hydration": ">=2.0.0-beta.4"
  },
  "devDependencies": {
    "@babel/core": ">=7.18.9",
    "@babel/eslint-parser": ">=7.18.9",
    "@babel/preset-env": ">=7.18.9",
    "@nuxt/types": "^2.15.8",
    "@nuxt/typescript-build": ">=2.1.0",
    "@nuxtjs/eslint-config-typescript": ">=10.0.0",
    "@nuxtjs/svg": ">=0.4.0",
    "@nuxtjs/tailwindcss": "^5.3.3",
    "@pinia/testing": ">=0.0.14",
    "@tailwindcss/line-clamp": "^0.4.0",
    "@testing-library/jest-dom": ">=5.16.4",
    "@types/google.maps": "^3.49.2",
    "@vue/eslint-config-airbnb": "^6.0.0",
    "@vue/runtime-dom": ">=3.2.39",
    "@vue/test-utils": "1.3.0",
    "@vue/vue2-jest": ">=29.1.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": ">=29.0.3",
    "core-js": "^3.24.1",
    "css-loader": "^5.2.0",
    "cypress": ">=10.4.0",
    "eslint": ">=8.20.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-import-resolver-jest": ">=3.0.0",
    "eslint-plugin-nuxt": ">=3.2.0",
    "eslint-plugin-vue": ">=9.3.0",
    "eslint-plugin-vuejs-accessibility": "^1.2.0",
    "flush-promises": ">=1.0.2",
    "jest": ">=29.0.3",
    "jest-context": ">=2.1.0",
    "jest-environment-jsdom": ">=29.0.3",
    "jest-extended": ">=3.1.0",
    "jest-localstorage-mock": ">=2.4.21",
    "jest-transform-stub": ">=2.0.0",
    "jest-when": ">=3.5.1",
    "node-sass": "^6.0.0",
    "sass-loader": "^10.3.1",
    "stylelint": "^13.13.1",
    "stylelint-scss": ">=4.3.0",
    "ts-jest": ">=29.0.1",
    "vue-tsc": ">=0.39.2"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead",
    "not IE 11"
  ]
}

my tsconfig

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "noImplicitAny": false,
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ],
      "~/*": [
        "./src/*"
      ],
      "@@/*": [
        "./*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/types",
      "@pinia/nuxt",
      "jest",
      "jest-extended",
      "@types/google.maps"
    ]
  },
  "exclude": [
    "node_modules",
    "cypress.config.ts",
    "cypress/**/*.ts"
  ]
}