Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Vue filters with jest

i'm trying to write a test for one of my filters in my Vue project using jest , can i Test that filter without using it in any component, i mean can i test it as a unit(like a function)? i searched a lot but i couldn't find anything to show me how to write an individual test for a filter in Vue

import Vue from 'vue'

export default function () {
    Vue.filter('englishNumber', (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
        })
    })
}

this is the filter i want to test does anyone know how to write this kind of test ?

like image 582
Hossein Karamzadeh Avatar asked Jan 23 '18 09:01

Hossein Karamzadeh


1 Answers

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 it
export 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 defintion
Vue.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")
  }
}
like image 156
brainbag Avatar answered Sep 22 '22 13:09

brainbag