How to convert Text to HTML in JavaScript function and unit test it with jest

733 Views Asked by At

I have found a JavaScript function which converts text to HTML. Here is the function

export default function ToText(node) {
  let tag = document.createElement("div");
  tag.innerHTML = node;
  node = tag.innerText;
  return node;
} 

I tried to test the function, but it is not working correctly. Here is my Testing script

import ToText from '../ToText';

it('check whether ToText function is working or not', () => {
  const a = "<P>This is a mock test for this function.</P>";
  const b = `This is a mock test for this function`;

  expect(ToText(a)).toBe(b);
});

What could be the reason it is not working, please help ?

3

There are 3 best solutions below

2
On

Variable a has a dot(.) at the end of the string. Variable b does not have it.

7
On

Just do this it might get solved

node= tag.firstChild.innerText
0
On

It should work with the plain text and not with the HTML. The ToText function is returning the innerText. If you want to change the changes you did then the ToText function needs to be changed.

import ToText from '../ToText';

it('check whether ToText function is working or not', () => {
  const a = "This is a mock test for this function";

  expect(ToText(a)).toBe(a);
});