unit-testing - 用 jest 测试 Vue 过滤器

标签 unit-testing testing vue.js vuejs2 jestjs

我正在尝试使用 jest 为我的 Vue 项目中的一个过滤器编写测试,我可以测试该过滤器而不在任何组件中使用它吗,我的意思是我可以将它作为一个单元(如函数)进行测试吗?我搜索了很多,但找不到任何东西可以告诉我如何在 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
        })
    })
}

这是我要测试的过滤器 有谁知道如何编写这种测试?

最佳答案

如果您正在编写在多个组件中使用的过滤器,那么测试就很容易了。

因为 Vue.filter 只需要一个函数,你可以通过导出定义来独立于过滤器编写一个函数测试,如下所示:

// 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)

然后在您的测试文件中,导入函数并像执行其他任何操作一样对其进行测试:

import { englishNumber } from '#/lib/filters.js'

describe("englishNumber") { 
  it("does whatever") {
    expect(englishNumber("actual")).toEqual("expected")
  }
}

关于unit-testing - 用 jest 测试 Vue 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48398816/

相关文章:

c# - 单元测试项目c#上的相对路径

angular - 测试ActivatedRoute.paramMap而不模拟路由器

python - 我应该如何构建一个 pytest 测试包?

node.js - Vue.js Heroku 部署无法正常工作

c# - Microsoft.VisualStudio.TestTools.UnitTesting 给出错误

泛型方法的 c# 单元测试

android - Espresso : String in adapterView

java - 在 junit 中使用@rule 检查错误代码

css - Vuetify 中的 BootstrapVue b-form-checkbox&radio 垂直中心?

vue.js - 如何在 nuxt.js 中使用 gtag.js?