cypress: Vue3 + Vite component test import error

Current behavior

When running a Vue3 component test with "@cypress/vite-dev-server": "^2.1.0" and "@cypress/vue": "^3.0.3" I see the following error on startup:

Failed to fetch dynamically imported module: http://localhost:3000/src/app/components/widgets/AdminTitle.cy.ts?import

This occurs about 75% of the time, but oddly works on occasion. It does not occur on hot reload when running with open-ct. The actual tests pass, but the error causes CI to fail and does not appear to be catchable with:

Cypress.on('uncaught:exception', (err, _runnable) => {
    return false
})

The error message from this issue is identical, but I’m not sure if the cause is related: https://github.com/lmiller1990/vue-3-cypress-vite/issues/1

Desired behavior

The error should not be thrown.

Test code to reproduce

It’s difficult for me to provide a demo project since the code is in a complex monorepo, but I will work on a minimal reproduction. I’m posting now in case there’s an obvious solution, or someone else has encountered the same problem.

AdminTitle.cy.ts

import { mount } from '@cypress/vue'
import { i18n, t, stubRouter } from '@cypress-local/support/stubs'
import AdminTitle from './AdminTitle.vue'

const router = stubRouter(['Home'])
const titleKey = 'name'

it('Shows the correct i18n text', () => {
  mount(AdminTitle, { props: { titleKey }, global: { plugins: [i18n, router] } })
    .get('.content-title')
    .contains(t('name'))
  cy.get('.button-back').should('not.exist')
})

it('Shows the back button', () => {
  mount(AdminTitle, {
    props: { back: 'DropsPage', titleKey },
    global: {
      plugins: [i18n, router],
    },
  })
    .get('.button-back')
    .should('exist')
})

AdminTitle.vue

<template>
  <div class="content-title-wrap">
    <ButtonBack v-if="back" :to="back" />
    <div class="content-title">
      {{ t(titleKey) }}
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

defineProps({
  back: {
    type: String,
    default: null,
  },
  titleKey: {
    type: String,
    required: true,
  },
})

const { t } = useI18n()
const router = useRouter()
</script>

cypress/support/stubs.ts

import { createI18n } from 'vue-i18n'
import { createRouter, createWebHistory, RouteRecordRaw, Router } from 'vue-router'
import en from '../../src/app/translations/en.json'

type MessageSchema = typeof en

export const i18n = createI18n<[MessageSchema], 'en'>({
  legacy: false,
  locale: 'en',
  messages: { en },
})

export const t = i18n.global.t
export const tm = i18n.global.tm

export const stubRoutes = (names: string[]): RouteRecordRaw[] =>
  names.map((name) => ({
    name,
    path: '/',
    component: {
      template: '<div>Test</div>',
    },
  }))

export const stubRouter = (routeNames: string[]): Router =>
  createRouter({
    history: createWebHistory(),
    routes: [...stubRoutes(routeNames)],
  })

cypress/plugins/index.ts

import { startDevServer } from '@cypress/vite-dev-server'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
module.exports = (on: any, config: any) => {
  on('dev-server:start', (options: Cypress.DevServerConfig) =>
    startDevServer({
      options,
    }),
  )

  return config
}

cypress.json

{
  "testFiles": "**/*.cy.{js,ts}",
  "componentFolder": "src/app",
  "viewportWidth": 800,
  "viewportHeight": 500,
  "video": false
}

Cypress Version

8.4.0

Other

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 4
  • Comments: 32 (6 by maintainers)

Most upvoted comments

I believe this is happening because vite does some magic and caches imports.

run-ct fails on the first try because there’s no cache and it refreshes(?), but on consecutive goes it succeeds. That’s a problem in CI and in headless mode, but not headful.

Reproducible by deleting node_modules/.vite folder before run-ct.

Hi, the issue still persists with Vite 2.9.8:

{
  "devDependencies": {
    "@cypress/vite-dev-server": "^2.2.2",
    "@cypress/vue": "^3.1.2",
    "@vitejs/plugin-vue": "^2.3.2",
    "cypress": "^9.6.0",
    "typescript": "^4.6.4",
    "vite": "^2.9.8"
  }
}

The following happens on the CI with cypress run-ct:

9:41:47 AM [vite] ✨ new dependencies optimized: vue
9:41:47 AM [vite] ✨ optimized dependencies changed. reloading
  1) An uncaught error was detected outside of a test
  0 passing (251ms)
  1 failing
  1) An uncaught error was detected outside of a test:
     TypeError: The following error originated from your test code, not from Cypress.
  > Failed to fetch dynamically imported module: http://localhost:3000/src/DCta.spec.ts?import
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
Cypress could not associate this error to any specific test.
We dynamically generated a new test to display this failure.

  DCta tests
    ✓ renders the DCta as a button when no props is passed (64ms)
    ✓ renders the DCta as a link (56ms)
    ✓ renders the DCta as a disabled button (40ms)

  (Results)
  ┌────────────────────────────────────────────────────────────────────────────────────────────────┐
  │ Tests:        1                                                                                │
  │ Passing:      0                                                                                │
  │ Failing:      1                                                                                │
  │ Pending:      0                                                                                │
  │ Skipped:      0                                                                                │
  │ Screenshots:  1                                                                                │
  │ Video:        true                                                                             │
  │ Duration:     0 seconds                                                                        │
  │ Spec Ran:     DCta.spec.ts                                                                     │
  └────────────────────────────────────────────────────────────────────────────────────────────────┘
====================================================================================================
  (Run Finished)
       Spec                                              Tests  Passing  Failing  Pending  Skipped  
  ┌────────────────────────────────────────────────────────────────────────────────────────────────┐
  │ ✖  DCta.spec.ts                             246ms        1        -        1        -        - │
  └────────────────────────────────────────────────────────────────────────────────────────────────┘
    ✖  1 of 1 failed (100%)                     246ms        1        -        1        -        -  

As explained by other commenters, the issue is appearing on the first page loading. Then, is seems to resolve the import successfully most probably due to vite caching.