Jest-dom: New custom matchers proposal

Created on 11 Apr 2018  路  3Comments  路  Source: testing-library/jest-dom

After a quick scan of the custom matchers provided in chai-dom I think there are many in there that I consider to be just for convenience and I do not favor adding them for the moment (for instance "to have id" and "to have value" are just a minor convenience over simply using .toHaveAttribute).

However, there are a few that I think could be good additions to this library. I think the overall criteria for what is considered a good addition is that doing the equivalent assertion on our own makes the test code more verbose and/or harder to read.

Here are some of the ones I see as convenient to add (all up for discussion):

  • expect(element).toBeEmpty(): the element exists but it contains no child elements. Not sure if that name is too generic outside of the scope of dom matchers. Also not sure if it's really just a convenience over a simple alternative with vanilla DOM APIs.
  • expect(element).toBeDisplayed(): asserts that display is not equal to "none".
  • expect(element).toBeVisible(): asserts that visibility is not "hidden" or "collapsed".

Additionally I wonder if instead of the last two, we could get away with a single .toHaveStyle that would work similar to .toHaveAttribute (e.g. .toHaveStyle('display', 'none'), .not.toHaveStyle('visibility', 'hidden'))

All 3 comments

I think the overall criteria for what is considered a good addition is that doing the equivalent assertion on our own makes the test code more verbose and/or harder to read.

This is a great guideline that could be added to the README.

I'm in favor of a toBeEmpty though I think we should come up with a different name to avoid name clashes.

I think we could just have expect(element).toBeVisible() and have it also check the display style. I don't see it as much of a difference to the expect(element).toBeDisplayed() matcher in practice (we're thinking about the user's experience after all and all that matters most of the time is whether it's visible.

I also like toHaveStyle. I think it'd be cool if that could also accept a style object and/or string to check multiple properties at once.

we're thinking about the user's experience after all and all that matters most of the time is whether it's visible

Very good point.

I'll add the guidelines to the README, and if no one else takes the task of some of these extra matchers, I'll eventually get to them.

I'll be closing this, as I opened more specific issues about the different new APIs discussed here ;)

6 toHaveStyle

7 toBeVisible

8 toBeEmpty

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hiwelo picture hiwelo  路  7Comments

gnapse picture gnapse  路  3Comments

gnapse picture gnapse  路  3Comments

kentcdodds picture kentcdodds  路  4Comments

maltebaer picture maltebaer  路  6Comments