Experimenting with Jest in a VueJS2 application that utilizes Typescript

I'm currently working on a VueJS 2 project and I've been trying to integrate TypeScript into it. The challenge I'm facing is setting up Jest tests for my components.

Here's a snippet of my TypeScript component:

<template>
    <div>some template<div>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
    
});
</script>

The build and serve process is functioning properly. However, when it comes to my spec file (just a dummy one named component.spec.ts):

import { shallowMount} from '@vue/test-utils';
//@ts-ignore
import Form from "@/MyComponent";

describe("Solicitacao Form component", () => {

    let wrapper: any;
  
    beforeEach(() => {
        wrapper = shallowMount(Form, {
        });
    })
    test('Component created', () => {
        expect(wrapper).toBeDefined();
    })

})

Every time I run the test, it throws an error message saying:

Test suite failed to run Jest encountered an unexpected token This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

Here's an excerpt from my jest.config.js file:

module.exports = {
    preset: "@vue/cli-plugin-unit-jest/presets/typescript-and-babel",
    //testEnvironment: 'node',
    setupFiles: ["<rootDir>/tests/unit/index.js"],
    moduleFileExtensions: ["js", "ts", "vue", "json"],
    transform: {
        ".*\\.(vue)$": "vue-jest",
        "^.+\\.ts?$": "ts-jest",
        "^.+\\.js$": "babel-jest"
    },
    moduleNameMapper: {
        "^@/(.*)$": "<rootDir>/src/$1"
    },
    testMatch: [
        "**/tests/unit/**/*.spec.(js|jsx|ts|tsx)"
    ]

}

Any suggestions on how to resolve this Jest setup issue?

Answer №1

If you're looking for some guidance on using jest/vue/ts, here's a helpful setup for you ;)

jest.config.js

module.exports = {
  verbose: true,
  preset: '@vue/cli-plugin-unit-jest',
  collectCoverage: true,
  collectCoverageFrom: [
    'src/**/*.{ts,js,vue}'
  ],
  coveragePathIgnorePatterns: [
    '!src/main.ts',
    '!src/router.ts',
    '!src/plugins/*',
    '!src/types/*',
    '!src/model/*',
    '!*.d.ts',
  ],
  coverageReporters: ['html', 'text', 'lcov'],
  rootDir: '../..',
  moduleFileExtensions: ['js', 'json', 'ts', 'vue'],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '^.+\\.vue$': 'vue-jest',
    '^.+\\.tsx?$': 'ts-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  setupFilesAfterEnv: ['./tests/unit/tools'],
}

Here's an example test for a simple component :

import { shallowMount } from '..';
import Maintenance from '@/components/Maintenance.vue';

describe('Maintenance.vue', () => {
  describe('getPositionStyle', () => {
    it('should be empty', () => {
      const component = shallowMount(Maintenance).vm
      expect(component.getPositionStyle()).toEqual('')
    })
  })
})

shallowMount file (index.ts)

import { shallowMount as shallowMountTestUtil, createLocalVue, ThisTypedShallowMountOptions } from '@vue/test-utils';
import { setupI18n } from './stub-i18n';
import { VueConstructor } from 'vue/types/umd';
import Vue from 'vue';

const localVue = createLocalVue();
const i18n = setupI18n(localVue);

export function shallowMount(component: VueConstructor, options: ThisTypedShallowMountOptions<Vue> = {}, mocks?: any, customLocalVue?: typeof Vue) {
  return shallowMountTestUtil(component, {
    localVue: (customLocalVue || localVue),
    i18n,
    ...options,
    mocks
  })
}

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

Want to learn how to integrate React-pdf (@react-pdf/renderer) with TypeScript on NodeJS and Express JS?

I am encountering difficulties running React-Pdf (@react-pdf/renderer) with TypeScript on an Express JS server. I have attempted to use babel but encountered errors that I cannot resolve. build error error error You can find the Github repository for t ...

"Ensuring the right data type is selected for the onChange event

In my code, I have a simple select component set up like this. import { Controller } from "react-hook-form"; import Select, { StylesConfig } from "react-select"; //.. const [universe, setUniverse] = useState<SetStateAction<TOptio ...

The directory containing compiled assets in a simple Vue.js project is known

After creating a basic vue.js application using Visual Studio 2019, I uploaded it to a git repository on my private Azure server. I am using a Windows build agent and have set up a YAML configuration for building without errors. trigger: - master pool: &a ...

Is there a way to redirect a user automatically if they are already logged in with Vue and Firebase authentication?

Description I am currently working on a feature to automatically redirect users to the "Games.vue" component if they are already logged in. My authentication system is built using Firebase, and I use the following code snippet to check if a user is logged ...

error encountered with lazy loading while interacting with modal components

Hey there! I'm currently working on implementing lazy loading with a modal component. Here's how my shared components module looks like: @NgModule({ declarations: [ AddNoteComponent, EditNoteComponent ], imports: [ IonicModu ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Bidirectional data binding with a nested object property. (Using VueJS and VueX)

I'm currently working on the following code snippet: <script> export default { computed: { editingItem: { get() { return this.$store.getters['editing/editingItem']; }, set(newValue) { this.$stor ...

Transform current JSON data into formatted JSON format using JavaScript or TypeScript

I have a JSON structure that needs to be reformatted in order to meet the requirements of an external service. Although the current format is complex and cannot be altered, I need to modify it to match the desired output for the external service. Current ...

Using TypeScript to Trigger Events in Three.js

After recently diving into Typescript, I encountered an issue when using EventEmitter from the ThreeJS library. Whenever I attempt to trigger an event: const event: THREE.EventDispatcher = new THREE.EventDispatcher(); event.addEventListener('test&apo ...

Utilizing Typescript DOM library for server-side operations

I've been working on coding a Google Cloud Function that involves using the URL standard along with URLSearchParams. After discovering that they are included in the TypeScript DOM library, I made sure to add it to my tsconfig file under the lib settin ...

It appears that tsc is failing to recognize the "exclude" directives specified in the tsconfig.json file

I'm having difficulty with tsc recognizing my tsconfig.json file and compiling my .ts files. I keep encountering duplication errors that I'm trying to prevent using my tsconfig.json. Here's what I have: package.json tsconfig.json typings.j ...

Issue with handling multiple input files in an *ngFor loop

I am facing difficulties in targeting the correct input within a *ngFor loop. When I include an image with the first input (Certificat dimmatriculation), it displays a placeholder image and a delete button to reset the input, but it appears under both divs ...

Exploring Array Iteration in a subscribe and ngOnInit Function

I'm facing a challenge where I need to iterate through an .subscribe() method placed inside an ngOnInit() method: ngOnInit() { this.service.getEmployees().subscribe( (listBooks) => { this.books = listBooks var events: C ...

Adding a dynamic route prefix in Nuxt.js: A step-by-step guide

Looking to integrate a dynamic language feature using an API. The API will provide a list of languages, and each language except "en" should have a route prefix. For instance: en: https://mynuxt.com/hotel/paris-hotel de: https://mynuxt.com/de/hotel/pari ...

"Utilizing Vue.js for Managing Foreign Keys in Database Entries

I am currently utilizing input in Vue.js. The structure of this input is as follows: induk_id:'', nama_barang:'', qtt:'', satuan:'', har ...

The issue with the vue-carousel arises from an uncaught TypeError in which it is unable to read properties of undefined while trying to access '_c'. This problem occurs within the vue-carousel.min.js file

I encountered an error when using the Carousel component from the plugin. The error message is as follows: vue-carousel.min.js:6 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_c') at Proxy.r (vue-carousel.min.js: ...

The error message indicates that the property `v.context.$implicit` is not callable

I am a beginner with Typescript and it has only been 3 days. I am trying to access data from Firebase and display it in a list. However, I keep encountering an error when trying to navigate to another page using (Click) ="item ()". Can someone point out wh ...

Vuex employs keys for retrieving objects from the state

I have the following code implemented in Vuex for a store. It works perfectly fine when structured like this: state: { APIData: {}, }, getters: { getFeed: state => {return state.APIData }, }, mutations: { SET_FEED_DATA(state, {folder_id, dat ...

Collaborating on data through module federation

Currently, I am in the process of developing a Vue.js and TypeScript application using Vite. In addition, I am utilizing the vite-module-federation-plugin for sharing code across different applications. My main inquiry revolves around whether it is possibl ...

What is the best way to dynamically add a new item to an object in Typescript?

var nodeRefMap = {}; function addNodeRef(key: String, item: Object){ console.log("Before:"); console.log(nodeRefMap); nodeRefMap = Object.assign({key: item}, nodeRefMap); console.log("After:"); console ...