Error in Jest Testing: An unexpected character '@' was encountered

Encountering issues with NuxtJS Jest tests and attempting to build a Nuxt app to test URL's due to route name errors in some components. Here is the code snippet I tried:

beforeAll(async () => {
  nuxt = new Nuxt({ ...config, server: { port: 3001 } })

  await nuxt.ready()

  await new Builder(nuxt).build()

  await nuxt.server.listen(3001, 'localhost')
}, 30000)

However, an error occurs related to nuxt-property-decorator not rendering @Component blocks:

ERROR in ./components/Menu/PrimaryNavigation.vue?vue&type=script&lang=ts& (./node_modules/vue-loader/lib??vue-loader-options!./components/Menu/PrimaryNavigation.vue?vue&type=script&lang=ts&) 16:0
Module parse failed: Unexpected character '@' (16:0)
File was processed with these loaders:
 * ./node_modules/vue-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| import PrimaryNavigationItem from '~/components/Menu/PrimaryNavigationItem.vue'
| 
> @Component({
|   components: { PrimaryNavigationItem },
| })

Shown below is my Nuxt.config.js:

import colors from 'vuetify/es5/util/colors'

export default {
  // Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
  ssr: false,

  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    ...
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  ...

  // Auto import components: https://go.nuxtjs.dev/config-components
  ...

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  ...

  // Modules: https://go.nuxtjs.dev/config-modules
  ...

  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  ...

  // Proxy
  ...

  // Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify
  ...

  // Build Configuration: https://go.nuxtjs.dev/config-build
  ...
}

Additionally, here is the Jest config used:

module.exports = {
  moduleNameMapper: {
    ...
  },
  moduleFileExtensions: ['ts', 'js', 'vue', 'json'],
  transform: {
    ...
  },
  collectCoverage: true,
  collectCoverageFrom: [
    ...
  ],
  setupFiles: ['<rootDir>/test/unit/index.js'],
}

Answer №1

Here are the steps you need to follow:

Firstly, ensure that you have both nuxt-ts and nuxt-property-decorator installed in your project using npm or yarn. Next, make sure that the following files are configured as shown below.

jest.config.js

module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1'
  },
  transform: {
    '^.+\\.ts?$': 'ts-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  moduleFileExtensions: ['ts', 'js', 'vue', 'json'],

  collectCoverageFrom: [
    'components/**/*.vue',
    'layouts/**/*.vue',
    'pages/**/*.vue',
    'lib/**/*.ts',
    'plugins/**/*.ts',
    'store/**/*.ts'
  ]
};

If you do not have one already, create tsconfig.js with the following configuration:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": [
      "esnext",
      "esnext.asynciterable",
      "dom"
    ],
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noImplicitAny": false,
    "resolveJsonModule": true,
    "noEmit": true,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./*"
      ],
      "@/*": [
        "./*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/types",
      "@types/jest"
    ]
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting unexpected behavior with Custom Guest middleware in Nuxt Project

I have implemented the Nuxt auth module for my project. To manage the login page, I created a custom middleware called guest.js, which has the following code: export default function ({ $auth, store, redirect }) { if (!process.server) { if ($auth ...

Unable to proceed with deployment due to the absence of the 'category' property in the '{}' type

Everything seems to be functioning properly - I can add and remove products, all with the properties I specified in the database. However, my deployment for production is being hindered by some errors that I'm encountering. ERROR in src\app&bsol ...

Is there a way to specify a type for a CSS color in TypeScript?

Consider this code snippet: type Color = string; interface Props { color: Color; text: string; } function Badge(props: Props) { return `<div style="color:${props.color}">${props.text}</div>`; } var badge = Badge({ color: &ap ...

NextAuth is failing to create a session token for the Credential provider

Currently, I am in the process of developing an application using the t3 stack and am facing a challenge with implementing the credential provider from nextauth. Whenever I attempt to log a user in, I encounter an error in the console displaying the messag ...

An error occurred with useState and localStorage: the parameter type 'string null' cannot be assigned to a parameter of type 'string'

I am currently using NextJS and attempting to persist a state using localStorage. Here is my code implementation: const [reportFavorite, setReportFavorite] = useState([ 'captura', 'software', 'upload', ] as any) ...

Incorporating a particular JavaScript library into Angular 4 (in case the library doesn't have a variable export)

I am attempting to display the difference between two JSON objects in an Angular 4 view. I have been using a library called angular-object-diff, which was originally created for AngularJS. You can view a demo of this library here: Link I have trie ...

Use v-bind to redirect to Localhost rather than the original link

The current button is linked to the data from v-for="book in books". The URL in the database is www.google.com. <md-button v-bind:href="book.url" target="_blank">SEE ORIGINAL</md-button> However, when loading the page on localhost, the butt ...

Using ngFormModel with Ionic 2

How can I properly bind ngFormModal in my Ionic 2 project? I am facing an issue while trying to import it on my page, resulting in the following error message: Uncaught (in promise): Template parse errors: Can't bind to 'ngFormModel' since ...

Async pipe in Angular does not work with my custom observables

I've been trying to implement the async pipe in my template, but I'm encountering difficulties retrieving data from my API. To store and retrieve the data, I have utilized a behavior subject to create an observable. However, when I attempt to dis ...

How can you correctly make an Ajax request using computed properties sourced from VueX Store?

Is there a way to make an AJAX call where one of the parameters is a computed State in VueX? For instance, if I use this.$axios.get('someUrl/' + accID ), with accID being a computed property from VueX (using MapState), sometimes it returns ' ...

Display an API generated popup list using Vue's rendering capabilities

I'm attempting to generate a pop-up within a displayed list using custom content retrieved from an API request. Currently, my code looks like this: <template> <div class="biblio__all"> <a v-for="i in items" ...

The promise briefly returns a placeholder object before resolving with the actual response

Currently, I am working on a simple check to determine whether myAnswer contains an answer. The checking functionality is operating smoothly; however, the issue arises in the final function that aims to return the string obtained from myAnswer. Instead of ...

Utilize @db.Decimal within the Prisma framework for the parameters "s", "e", and "d"

When I define the schema in Prisma like this: value Decimal? @db.Decimal(7, 4) Why do I always get this format when retrieving the value from the database: "value": { "s": 1, "e": 0, & ...

Updating the project version in package.json using Vue CLI

I'm facing a seemingly simple task, but it's proven to be hard to find the right information online. Most resources I come across talk about updating NPM versions or dependencies, rather than simply changing the project version in package.json. ...

Implementing anchor tags in VueJS Swiper

Regarding a VueJS 2.0 project using Swiper v8.3.2, there is an issue with a swiperSlide that resembles the following code: <template> <a :href="url" :title="title" >{{ title }}</a> </template> How ca ...

The error message states that the type '{}' does not contain the property 'API_BASE_URL'

Encountering this error message when trying to access my API_URL as defined in the enviroment.ts file within a service class. Error: src/app/product/product.service.ts:12:25 - error TS2339: Property 'API_BASE_URL' does not exist on type '{} ...

Working with Array of Objects Within Another Array in Angular 6 Using Typescript

I'm currently working with an array of "food": "food": [ { "id": 11, "name": "Kabeljaufilet", "preis": 3.55, "art": "mit Fisch" }, { "id": 12, "name": "Spaghetti Bolognese", "preis": 3.85, "art": "mit Fleisch" }, { "id": 1 ...

Tips for showing a universal loading indicator for every axios request in a Nuxt plugin

Is there a way to implement a custom loading feature for all axios requests globally? I've developed a plugin for axios that can be used like this: plugins/axios.js export default function ({ app, $axios, redirect, store }, inject) { $axios ...

Monitoring the loading progress of multiple files using Three JS

Just starting out with Three JS and I'm on a mission to create a loading screen that displays the progress of assets being loaded for a scene. I have a total of 7 different types of assets, including: 4 GLB files 2 Texture files And 1 Obj file Acco ...

Troubleshooting the error message "TypeError: Cannot read property 'name' of undefined" when working with data binding in Angular 4

I am brand new to Angular and I have been working on creating a custom Component. Specifically, I am trying to display a list of Courses (objects) which consist of two properties: id and name. So far, this logic is functioning properly. However, when attem ...