You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

vue-test-utils弃用setComputed后,如何设置单元测试的Vue计算属性?

How to Set Computed Properties in Vue Test Utils (After setComputed Was Deprecated)

I've run into this exact confusion too—when setComputed() got deprecated in Vue Test Utils 1.x, the error message mentions using a computed object in mounting options, but the docs didn't catch up right away. Those two syntaxes you tried won't work because VTU 1.x doesn't actually support a top-level computed option or a context.computed path in mount options.

Here are the two reliable ways to override computed properties for your tests:

1. Extend the Component to Override Computed Properties

The most straightforward approach is to create an extended version of your component where you redefine the computed property you need to control:

import { mount } from '@vue/test-utils'
import Home from '@/components/Home.vue'

// Create an extended component with our overridden computed property
const TestableHome = {
  extends: Home,
  computed: {
    loaded() {
      return true // Force this computed property to return true for the test
    }
  }
}

// Mount the extended component instead of the original
const wrapper = mount(TestableHome)

This works because we're leveraging Vue's component extension system to overwrite the specific computed property without modifying the original component file.

2. Mock Dependencies (For Computed Properties That Rely on Global State)

If your loaded computed property depends on global state (like Vuex getters, Vue Router, or other injected properties), use the mocks mounting option to simulate those dependencies:

import { mount } from '@vue/test-utils'
import Home from '@/components/Home.vue'

const wrapper = mount(Home, {
  mocks: {
    // Example: If your computed property uses a Vuex getter
    $store: {
      getters: {
        loaded: true
      }
    }
  }
})

This is useful when the computed property's value is derived from external state—instead of overriding the computed property itself, you mock the source it relies on.

The error message's mention of a computed mounting option was likely a bit premature or poorly worded; the component extension method is the officially recommended alternative once setComputed() is removed.

内容的提问来源于stack exchange,提问作者Harold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:11:51