[Vuejs]-How to test truncate filter with Jest?

0👍

As you’re using a global filter, you can use a seperate function and import it in your test easily.

First, split up the filter:

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

Then import & use that function in your test, e. g.:

import { truncate } from '../filters.js';

describe("filter") { 
  it("truncates the text") {
    expect(truncate("your text", 5, "your clamp")).toEqual("expected")
  }
}

0👍

Here’s How I’ve

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

and here’ the test code :

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

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

Leave a comment