preact-jsx-chai icon indicating copy to clipboard operation
preact-jsx-chai copied to clipboard

Indentation works against `contains` test

Open tomascasas opened this issue 7 years ago • 5 comments

I found myself testing a component with nested components which I decided to mock. The component also returns a "lot" of html. That is why I decided to test the component contains certain pieces instead of for equality.

This is a valid example of the issue:

class MyComponent extends Component {
  render({imgUrl}) {
    return (
      <div>
        <img src={imgUrl}/>
      </div>
    )
  }
}

expect(<MyComponent imgUrl="http://url" />).to.contain(
  <img src="http://url"/>
)

The test will fail due to rendering of MyComponent vs. the contained render indents differ. See: MyComponent output:

<div>
  <img src="http://url"/>
  </img>
</div>

Test JSX output:

<img src="http://url"/>
</img>

I think the easiest fix is to prevent indentation when using contains test. Output will not look nice but would still allow to have the test passing.

tomascasas avatar Apr 20 '17 17:04 tomascasas

I see the dependency to preact-render-to-string, and onRender opts should take care of that. Will report back.

tomascasas avatar Apr 20 '17 22:04 tomascasas

Just went through code one more time and I realized it is pulling preact-render-to-string/jsx to render and that attributeHook function (default option) is the one introducing the \n that prevents from returning a single line output. Can you help me understand why you use that import instead of the default preact-render-to-string?

tomascasas avatar Apr 21 '17 00:04 tomascasas

That import preserves component names and applies formatting to complex attribute values (prop values), including the ability to serialized JSX within props. I think we'll need to make the comparison in this repo intelligent enough to strip leading/trailing whitespace.

developit avatar Apr 21 '17 17:04 developit

I'll see if I can help. Will go through preact-render-to-string/jsx/attributeHook again. Thanks!

tomascasas avatar Apr 21 '17 23:04 tomascasas

Ah actually it looks like this is a bug that was recently introduced in preact-render-to-string. The following condition turns <img></img> into <img /></img>, which is incorrect and breaks your comparison: https://github.com/developit/preact-render-to-string/blob/master/src/index.js#L161-L163

developit avatar Apr 22 '17 18:04 developit