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

Vue Test Utils自定义过滤器报错:this.$options.filters.customCurrency不是函数

解决Vue Test Utils中过滤器未找到的报错问题

首先注意你组件代码里的笔误:this.$options.filterks应该是this.$options.filters,拼写错误也会导致找不到过滤器,先修正这个问题。

针对测试时的过滤器模拟/存根,有三种常用方法:

方法一:全局注册过滤器(和生产环境一致)

在测试文件开头,和生产代码一样注册全局过滤器,所有测试组件都能访问到:

import Vue from 'vue';

// 注册全局过滤器,仅保留基础实现即可
Vue.filter('customCurrency', (currency) => currency);

方法二:挂载组件时局部存根过滤器

挂载组件时,通过filters选项给当前组件实例添加过滤器,仅作用于当前测试:

import { shallowMount } from '@vue/test-utils';
import YourComponent from '@/components/YourComponent.vue';

describe('YourComponent', () => {
  it('测试组件逻辑', () => {
    const wrapper = shallowMount(YourComponent, {
      filters: {
        customCurrency: (currency) => currency // 存根简单实现
      }
    });

    // 后续测试逻辑
  });
});

方法三:直接模拟组件实例的$options.filters

如果需要动态修改或模拟,可直接操作组件实例的$options.filters:

import { shallowMount } from '@vue/test-utils';
import YourComponent from '@/components/YourComponent.vue';

describe('YourComponent', () => {
  it('测试组件逻辑', () => {
    const wrapper = shallowMount(YourComponent);
    
    // 模拟过滤器函数
    wrapper.vm.$options.filters.customCurrency = (currency) => currency;

    // 触发依赖该过滤器的逻辑
    wrapper.vm.someMethodThatUsesFilter();
    
    // 断言测试结果
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:35:30