Home > front end >  how extract value from calc function in tests
how extract value from calc function in tests

Time:11-30

I am trying to create a test in which I want to compare the width of an element after it has been resized by dragging it. The problem is that the resize library returns the width value as

calc(50% - 4px)

The only thing that changes is this percentage value and this is what I want to compare in the test if it is bigger or smaller depending on the mouse movement to the right or left.

However, I do not know how to extract only the percentage value or possibly the subtraction result from this string.

  it("has resizable containers", async () => {
    const initialRightWith = rightContainer.style.width;
    expect(initialRightWith).toEqual("50%");
  });

Expected: "50%" Received: "calc(50% - 4px)"

CodePudding user response:

You could use a regular expression to get the percentage from your string, here's an example:

const width = 'calc(50% - 4px)';
const regex = /^calc\((\d{1,3})%. $/;

const getPercentageFromCalc = (w) => {
  const matches = regex.exec(width);
  
  return matches[1];
};

console.log(getPercentageFromCalc(width));

Remember to add checks to make sure your regular expression matched something, this is just an example!

  • Related