Error message: Cypress Vue component test fails due to the inability to import the Ref type (export named 'Ref' is missing)

Recently, I created a Cypress component test for my Vue component by mounting it and verifying its existence. The component utilizes Vue's Ref type and is structured as a TypeScript component.

However, during the test execution, Cypress encountered an error:

An export named 'Ref' was not found in the requested module '/__cypress/src/node_modules/.vite/deps/vue.js?v=861dc0d7'

I've already updated the types in my Cypress tsconfig.json to include 'vue', but haven't been able to resolve this issue.

tsconfig.json
---
{

  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": ["cypress", "vue", "node"],
    "baseUrl": "./",
    "allowJs": true,
    "paths": {
      "~": ["."]
    },
  },
  "include": ["**/*.ts", "**/*.js"]
}

Below is my Cypress configuration:

cypress.config.js
---
const { defineConfig } = require("cypress")

module.exports = defineConfig({
    component: {
        supportFile: "cypress/support/component.ts",
        devServer: {
            framework: "vue",
            bundler: "vite",
        },
    },
})

The component code snippet:

MyComponent.vue
---
<template>
    <div class="my-component">
        {{ counter }}
    </div>
</template>

<script setup lang="ts">
import type { Ref } from "vue"

const counter: Ref<number> = ref(1)
</script>

Here's how the test is implemented:

MyComponent.cy.ts
---
import MyComponent from "./MyComponent.vue"

beforeEach(() => {
    cy.mount(MyComponent)
})

it("Test My Component", () => {
    cy.get(".my-component").should("exist")
})

Answer №1

Within your Typescript project, the presence of cypress.config.js suggests that Cypress may not be configured to use Typescript (import type {Ref} is invalid syntax in javascript).

If I were to incorporate your component into a running Typescript project with cypress.config.ts and appropriate adjustments, it would then recognize the type import.

(Please note that I am using an older version of Vue)

import { defineConfig } from "cypress";

export default defineConfig({
  component: {
    devServer: {
      framework: "vue-cli",
      bundler: "webpack",
    },
  },
})

In addition, you will need to include an import for the specific ref within the component

<script setup lang="ts">
import type { Ref } from "vue"
import { ref } from "vue"            <-- add this 

const counter: Ref<number> = ref(1) 
</script>

Answer №2

After investigating further, I identified the root cause of the problem. It appears that in my tsconfig.json configuration file, I was extending from Nuxt's tsconfig (

"extends": "./.nuxt/tsconfig.json"
)

By removing this line from the configuration file, the issue was successfully resolved.

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

You must use the 'new' keyword in order to invoke the class constructor

Although similar questions have been asked before, my situation differs from the typical scenarios. I have a basic base class named CObject structured as follows: export class CObject extends BaseObject { constructor() { super(); } sta ...

Tips on ensuring the <script> section of a Vuejs single file component loads prior to the <template> section

After posing my query here, I have come to the realization that the root of my problem might be due to the template loading before the script. This causes an error when it encounters an undefined variable, halting the script execution. The issue could pote ...

What is the best way to link three different types of http requests in succession and adaptively?

Is it possible to chain together 3 types of http requests correctly, where each request depends on data from the previous one and the number of required requests can vary? In my database, there is a team table with a corresponding businessId, a supervisor ...

Implementing Pagination in Vuetify: A Step-by-Step Guide

I am looking to implement pagination using the Vuetify framework in my VueJS project. The Vuetify Pagination component: <v-pagination v-model="pagination.page" :length="pagination.total / 5" :total-visible="pagination.visible" ...

Getting information from my RESTful API and populating the array data property in my VueJS component

For several weeks, I've been immersed in learning Vue.js and building a Rest API backend using NodeJS express, which I'm eager to integrate. After successfully setting up the Rest API to deliver JSON data, my next challenge is to retrieve that js ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

Ionic - Smooth horizontal tab scrolling for sorted categories

Currently, we are developing a web/mobile application that includes horizontal scroll tabs to represent Categories. While this feature works well on mobile devices, it requires additional functionality for web browsers. Specifically, we need to add two arr ...

How can I automatically close the menu when I click on a link in Vue?

Tap the menu icon Select a link The URL changes in the background. However, the menu remains open. How do I close the menu when a link is selected? The menu is wrapped in a details HTML element. Is there a way to remove the "open" attribute from the detai ...

Issues with TypeScript Optional Parameters functionality

I am struggling with a situation involving the SampleData class and its default property prop2. class SampleData { prop1: string; prop2: {} = {}; } export default SampleData; Every time I attempt to create a new instance of SampleData without sp ...

"What is the most effective way to utilize and integrate the `setValue` function from react-hook-form within a custom react hook

Struggling to pass setValue to a react hook? In my custom react hook, I need to set values in a form using react-hook-form's setValue. Yet, after migrating from v6 to v7, I'm having trouble figuring out the proper typing for this. This is how t ...

Error message: Injector Error: R3InjectorError(Standalone[_AppComponent])[_WebService -> _WebService -> _WebService] occurred

Being a student, I must apologize in advance for any mistakes in terminology or gaps in my understanding. I am currently developing an Angular front-end to communicate with my backend API. However, I keep encountering the following error in the web page c ...

How can I send an array of date and time values from a Vue.js component to an ASP.NET Core API?

Here is my API code snippet: [HttpGet("/GetBusinessDaysWithPublicHolidayDates/")] public int GetBusinessDays(DateTime startDate, DateTime endDate,[FromQuery] IList<DateTime> publicHolidays) { var noOfDays = _dayCalculatorService.Busines ...

Using TypeScript: creating functions without defining an interface

Can function props be used without an interface? I have a function with the following properties: from - HTML Element to - HTML Element coords - Array [2, 2] export const adjustElements = ({ from, to, coords }) => { let to_rect = to.getBoundingC ...

Plugin for managing network connectivity in Ionic framework

In order to check if internet and id connection are available, I need to make a server request. I have implemented the Ionic Native Network Plugin following their official documentation. Here is my code snippet: import { Component } from '@angular/c ...

Stop the div from collapsing when hiding or deleting all child elements to maintain its structure

I have recently developed a Vuetify application that manages card items. To ensure security and accessibility, I have added a feature where the actions/buttons are displayed based on the User's permissions. In case of missing permissions, these button ...

Developing in TypeScript with styled-components allows for seamless integration between

New to TypeScript and seeking guidance. I currently have a component utilizing styled-components that I want to transition to TypeScript. import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-comp ...

Error: The specified property is not found in type 'never' - occurring with the ngFor loop variable

When working with API responses and dynamically sorting my view, I utilize an ngFor loop. Here's the snippet of code in question: <agm-marker *ngFor="let httpResponses of response" [latitude]= "httpResponses.lat" [longitude]=& ...

The parameter of type 'never' cannot be assigned with the argument of type 'number | boolean | undefined'

In my project, I am creating a validation input using TypeScript in Next.js. interface InputRules { required?: boolean min?: number max?: number minLength?: number maxLength?: number } I have defined an object that contains methods to handle val ...

The variable "theme" is referenced prior to being initialized

https://i.stack.imgur.com/QL0pa.png One of the variables in my code, theme, is set to be assigned a value from a for loop: let theme: Theme for (const themeObj of themeList) { const [muiThemeName, muiTheme] = Object.entries(themeObj)[0]!; if (muiThem ...

Encounter an error message stating "Request failed with status code 502 nginx in Next.js TypeScript."

After setting up Next.js typescript with Kubernetes NGINX Ingress, I encountered a problem where specific routes were returning a 502 error. For example, the route /test works fine, but /login does not. I'm unsure whether the issue lies with Kubernete ...