Search code examples
vue.jsnuxt.jsvitest

ReferenceError: computed is not defined on Vitest test suite


Description

I'm migrating test suites from Jest to Vitest. But i've a problem when i run test suites, an error occurs when a component has a computed property.

The common error is :

ReferenceError: computed is not defined

 - /components/Ui/Avatar.vue:13:30
 - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:157:22
 - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7084:29
 - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7039:11
 - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5401:13
 - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5376:17
 - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4978:21
 - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5515:21
 - /node_modules/@vue/reactivity/dist/reactivity.cjs.js:189:25
 - /node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5622:56

Versions

  • "vitest": "^0.18.1"
  • "jsdom": "^20.0.0"
  • "@vue/test-utils": "^2.0.2"

Exemple

Here is my component code :

<template>
  <image
    :src="src"
    :onerror="onErrorLoadImage"
    :class="['avatar', { big }]"
  />
</template>

<script setup lang="ts">
const props = withDefaults(defineProps<{
  src?: string
  big?: boolean
  errorImage?: string
}>(), {
  src: '',
  big: false,
  errorImage: '/no-avatar.png',
})

const onErrorLoadImage = computed(() => `this.src='${props.errorImage}';this.onerror='';`)
</script>

And my test

import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import UiAvatar from './Avatar.vue'

const componentName = 'img'
const src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='
const big = true
const errorImage = '/no-avatar.png'

describe('UiAvatar', () => {
  it('should be render the component', () => {
    const wrapper = mount(UiAvatar, {
      propsData: {
        src,
        big,
        errorImage
      }
    })
    expect(wrapper.element.tagName).toBe(componentName)
  })
})

Thanks :)


Solution

  • This can be solved by using the following npm packages: unplugin-vue-components/vite unplugin-auto-import/vite

    They only need to specify a path where the import files will be generated, in my case I use a storybook folder since I also use the plugin there, but it can be any other path

    vitest.config.ts