【问题标题】:How to test truncate filter with Jest?如何用 Jest 测试截断过滤器?
【发布时间】:2019-03-27 15:41:18
【问题描述】:

我需要用 Jest 测试这个过滤器。有什么帮助吗? 我的代码如下所示:

import Vue from "vue";

Vue.filter("truncate", (text, length, clamp) => {
    text = text || "";
    clamp = clamp || "...";
    length = length || 30;

    if (text.length <= length) return text;

    let tcText = text.slice(0, length - clamp.length);
    let last = tcText.length - 1;

    while (last > 0 && tcText[last] !== " " && tcText[last] !== clamp[0])
        last -= 1;

    // Fix for case when text dont have any `space`   last = last || length - clamp.length;
    tcText = tcText.slice(0, last);
    return tcText + clamp;
});

【问题讨论】:

  • 您能否更具体地提出您的问题?你遇到了什么问题?

标签: javascript unit-testing vue.js jestjs


【解决方案1】:

这就是我的经历

截断.js

import Vue from 'vue'

export const truncate = (text, length, clamp) => {
  text = text || "";
  clamp = clamp || "...";
  length = length || 30;

  if (text.length <= length) return text;

  let tcText = text.slice(0, length - clamp.length);
  let last = tcText.length - 1;

  while (last > 0 && tcText[last] !== " " && tcText[last] !== clamp[0])
    last -= 1;

  // Fix for case when text dont have any `space`   last = last || length - clamp.length;

  tcText = tcText.slice(0, last);

  return tcText + clamp;
};

Vue.filter("truncate", truncate);

这里是测试代码:

import Vue from 'vue'
import { truncate } from '@/filters/truncate.js'

describe("truncate",() =>{
  it("truncates the text", ()=> {
    expect(truncate("putSomeTextHere", 5, "...")).toEqual("pu...");
   });
  });

【讨论】:

    【解决方案2】:

    当您使用全局过滤器时,您可以使用单独的函数并将其轻松导入到您的测试中。

    首先,拆分过滤器:

    export const truncate = (text, length, clamp) => {
      text = text || "";
      clamp = clamp || "...";
      length = length || 30;
    
      if (text.length <= length) return text;
    
      let tcText = text.slice(0, length - clamp.length);
      let last = tcText.length - 1;
    
      while (last > 0 && tcText[last] !== " " && tcText[last] !== clamp[0])
        last -= 1;
    
      // Fix for case when text dont have any `space`   last = last || length - clamp.length;
    
      tcText = tcText.slice(0, last);
    
      return tcText + clamp;
    };
    
    Vue.filter("truncate", truncate);
    

    然后在您的测试中导入并使用该功能,例如。 g.:

    import { truncate } from '../filters.js';
    
    describe("filter") { 
      it("truncates the text") {
        expect(truncate("your text", 5, "your clamp")).toEqual("expected")
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 2021-05-04
      • 2019-04-28
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2014-06-22
      • 2020-12-18
      • 1970-01-01
      相关资源
      最近更新 更多