如何用Jest测试截断过滤器?

时间:2018-10-23 11:51:40

标签: javascript unit-testing vue.js jestjs

我需要使用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;
});

2 个答案:

答案 0 :(得分:0)

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

首先,拆分过滤器:

select * 
  from stg_place.place a 
  left join stg_place.place_polygon b on 
   ST_DWithin (st_setsrid(st_make_point(long,lat),4326),b.geom,0);

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

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

答案 1 :(得分:0)

这就是我的生活

Truncate.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...");
   });
  });