Jest to test HTML String

18,592

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.

Share:
18,592
ivp
Author by

ivp

I am software engineer.

Updated on August 15, 2022

Comments

  • ivp
    ivp over 1 year

    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.