7

How do I test a HTML string using Jest?

Right now, I am doing it using regular string comparison like below. When I run this test case, it works fine.

it('should compile partial as per the context', () => {
  const receivedOutput = someFunctionReturningHTMLString();
  //*PS: someFunctionReturningHTMLString() is function which returns a html string;*
  //In above call, lets assume it returns `<a href="/" class="some_class1 some_class2" >`

  const expectedResult = `<a href="/" class="some_class1 some_class2" >`;
  expect(receivedOutput .trim()).toEqual(expectedResult.trim())
});

However, I don't find this approach of testing pure string values as a good approach.

Can somebody help me with a better way where I can actually test the content of the HTML string? Like testing whether the tag in the string has a particular class? Something like what we can achieve with Enzyme for React components.

1 Answer 1

14

Assuming we're talking about testing with jest and vanilla JS.

If you want to test that you're returning valid HTML from someFunctionReturningHTMLString (which I think it's what matters) another approach would be to create a DOM Element and insert the content returned in the node with innerHTML, then you'd be able to test it as normal HTML and make sure it's valid:

it('should compile partial as per the context', () => {
  const receivedOutput = someFunctionReturningHTMLString();

  // convert output to actual HTML
  const newNode = document.createElement('div');
  newNode.innerHTML = receivedOutput;

  // Assuming your output is `<a href="/" class="some_class1 some_class2" >`
  const link = newNode.querySelector('a');

  // Test the attributes that matter to you as normal HTML
  expect(link.getAttribute('class')).toBe('some_class1 some_class2')
  expect(link.getAttribute('href')).toBe('/')
});

Then it'd be pretty straightforward testing nested elements, text nodes and so on, hope it helps.

Jest's documentation have some examples of how to work with DOM Manipulation they use jQuery to demonstrate but the applied principle is what matters.

Sign up to request clarification or add additional context in comments.

1 Comment

Enmanuel, I almost did the same thing. I know this is an old post, but thank you for sharing and explaining the thoughts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.