Testing Vue filters with jest Testing Vue filters with jest vue.js vue.js

Testing Vue filters with jest


If you're writing filters used in multiple components, then it's quite easy to test.

Since Vue.filter simply takes a function, you can just write a test for the function independently of the filter by exporting the definition, like so:

// Define the function independently and export itexport const englishNumber = function (value) {  if (value === '۰') return 0  if (!value) return ''  if (typeof value !== 'string') {    value = value.toString()  }  return value.replace(/[\u06F0-\u06F9]+/g, function (digit) {    let ret = ''    for (let i = 0, len = digit.length; i < len; i++) {      ret += String.fromCharCode(digit.charCodeAt(i) - 1728)    }    return ret  })}// Pass the function in to the filter defintionVue.filter('englishNumber', englishNumber)

Then in your test file, import the function and test it like you do anything else:

import { englishNumber } from '#/lib/filters.js'describe("englishNumber") {   it("does whatever") {    expect(englishNumber("actual")).toEqual("expected")  }}


We can test filters with hand-made components. For example we have a filter that transform date into needed format:

// filters.jsimport Vue from "vue";Vue.filter("dateFormat", (incomingDate) => {  // does the work here}

So we can test it the following way:

// filters.spec.jsimport Vue from "vue";import "@/components/filters";import { mount, createLocalVue } from "@vue/test-utils";const myComponent = Vue.component("myComponent", {  data() {    return {      date: new Date("January 1, 2020 01:10:30")    };  },  template: "<p> {{ date | dateFormat }} </p>"});const localVue = createLocalVue();describe("filter dateFormat", () => {  it("filter transforms date to readable format", () => {    const wrapper = mount(myComponent, {      localVue    });    expect(wrapper.html()).toBe("<p> 01 January 2020 </p>");  });});


The correct way to unit test a Vue filter would be to declare it locally inside your component (using Vue's API and Vue.filter).You can then write unit tests inside your Vue component.You can check this case