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

Npm encountered an error while attempting to connect to the specified URL. The issue was caused by the SSL routines, as they have disabled unsafe legacy renegotiation

Having recently updated the version of Node JS for a Vue 3 application from Node V.16 to Node V.18, I encountered an issue after successfully updating via the *.exe installer. I found myself unable to execute the "npm install" or "npm login" command. When ...

Adding two comparable Objects in Javascript / vuejs

I have two objects and I want to add the values of each key separately with another object. Here's an example: CharacterStats: { a: 0, b: 2, c: 0, d: 0 } ItemStats: { a: 0, b: -1, c: 4, d: 0 } The expected result is: CharacterStats: { a: 0, b: 1, c: ...

Compiling in Vue.js can be a bit sluggish

npm run dev completes the task at a rapid pace. However, when I append 1000 rows of HTML content (header) to a .vue file's template section, it takes approximately 9 minutes for compilation. The burning question: Does vue.js struggle with handling ...

The component prop of Typography in TypeScript does not accept MUI styling

Working with MUI in typescript and attempting to utilize styled from MUI. Encountering an error when passing the component prop to the styled component. The typescript sandbox below displays the issue - any suggestions for a workaround? https://codesandbo ...

Tips for stopping Vue.js automatic merging of CSS classes

Recently, I embarked on my journey with Vue.js and have been thoroughly enjoying the experience. However, I've stumbled upon a challenge that has me stumped. Despite searching high and low and studying the documentation, I haven't found a solutio ...

When initializing a Vue application using the command 'vue create hello-world', the './fs' module is not found

After spending the last 3-4 hours trying to work with Vue, I'm finding it incredibly challenging just to get it up and running. I've been following the documentation provided here: https://cli.vuejs.org/guide/creating-a-project.html#vue-create ...

Power up your Vue.js app with Actions and Global Methods

I have been exploring the power of store actions in nuxt.js and I recently organized all my global methods and computed properties into a global mixin. Within this setup, I realized that I have numerous Axios requests fetching different products. Should I ...

Utilize a jest mock object and pass it as a method parameter to achieve seamless testing

I am attempting to create a mock object (ColumnApi from ag-grid) using jest and then pass it as a parameter to a function that calls the "getAllColumns" method from ColumnApi. I am not concerned with how the "getAllColumns" method functions, but I want it ...

Using `publishReplay()` and `refCount()` in Angular does not behave as anticipated when dealing with subscriptions across multiple components

I am currently investigating the functionality of publishReplay in rxjs. I have encountered an example where it behaves as expected: const source = new Subject() const sourceWrapper = source.pipe( publishReplay(1), refCount() ) const subscribeTest1 = ...

Passing Selected Table Row Model Data to Backend in Angular 7

My goal is to send the selected data in a table row, which I select through a checkbox, to the server. However, I'm unsure about how to handle this via a service call. While I have the basic structure in place, I need assistance with sending the items ...

Exploring the wonders of using the Async Pipe with Reactive Extensions

I'm facing a little issue with the async pipe in Angular. Here's my scenario: I need to execute nested observables using the async pipe in HTML because I'm utilizing the on-push change detection strategy and would like to avoid workarounds ...

Is it possible for OpenFin to store logs in a secure database and what is the process for accessing logs located at %LocalAppData%openfinapps<app>app.log

System Information Here are the details of the system setup: OpenFin Process Manager Version: RVM = 8.1.0.4 Node.js: v16.15.0 Windows 10 Angular Application with C# .NET backend Issue: The current setup saves all application logs locally on users' ...

Seeking a solution to the useRef problem. Encountering difficulties with React Hook useRef functionality within a NextJS application

Whenever I refresh the page, the 'Ref' value is displayed as null. This causes the if condition blocks not to work. I attempted to modify the useRef values but could only set it to null. When I console log the myDivRef.current, it returns "Ref: ...

The specified "ID" type variable "$userId" is being utilized in a positional context that is anticipating a "non-null ID" type

When attempting to execute a GraphQL request using the npm package graphql-request, I am exploring the use of template literals. async getCandidate(userId: number) { const query = gql` query($userId: ID){ candidate( ...

Exploring Appsetting Configuration in AppModule of Angular 8

I'm looking to update my configuration in the appsettings file by replacing a hardcoded string with a reference to the appsetting. Currently, I have this hardcoded value in appmodule.ts: AgmCoreModule.forRoot({ apiKey: 'testtesttest', li ...

What is the best way to incorporate external directives globally in Vue 3?

How can directives be added to a Vue 3 application so that they are globally accessible without the need to include them in each component individually? ...

Vue.js Dynamic Class Binding Fails to Update

As I delve into learning Vue Js, I have been working on a simple todo app. One interesting thing I've done is binding a class to my todo items based on whether todo.completed is true or not: <a v-bind:class="{iscomplete : todo.completed}& ...

Tips for determining the duration between the Monday of last week and the Sunday of last week

Can anyone help me figure out how to retrieve the dates from last week's Monday to last week's Sunday using JavaScript? I've searched through various sources with no luck. Hoping someone here can provide some guidance. ...

The argument provided for the foreach() function in Axios Laravel is not valid

I'm encountering an issue with my Vue.js form that uses Axios for submission. While I can successfully save the data to my database, I run into trouble when trying to save dynamically added input fields. The error message I receive is as follows: I ...

Using Font Awesome icons with Buefy for beautiful designs

Currently, I am in the process of transitioning my project from utilizing bulma + jQuery to buefy. The resources I am loading include buefy, vue, and font awesome from a CDN. However, despite specifying the defaultIconPack as 'fas' for font aweso ...