As discussed in #4, this library needs a .toHaveStyle custom matcher. It should receive an object of css properties and their values, and will pass if the element has all the css properties in that object with the expected values.
expect(element).toHaveStyle({
backgroundColor: '#fff',
height: '100%',
})
This should be implemented to take advantage of window.getComputedStyle to obtain all the styles applied to an element. This includes styles acquired from css classes applied to it, as well as styles applied directly via the style="..." attribute.
Also, this probably would have to deal with supporting css properties specified in camelCase, and covert them to the "kebab-case" before comparing them to the actual styles. It'd be nice to do that without adding too many external dependencies if possible, or better yet, none at all.
Doing the equivalent check with vanilla DOM APIs would be a bit verbose. It's not just about checking the style=".." attribute, and decode information out of it (which by itself would be even more verbose), but it involves using the DOM api mentioned above. Also the fact that it'd enable users to check for multiple style properties at the same time makes it even more useful, and the alternative even more verbose.
For instance, the above example would be something like this:
expect(getComputedStyle(element).getPropertyValue('background-color')).toEqual('#fff')
expect(getComputedStyle(element).getPropertyValue('height')).toEqual('100%')
I think it'd be super if it could also accept a string of css:
expect(element).toHaveStyle(`
background-color: #fff;
height: 100%;
`)
May need to use https://www.npmjs.com/package/css which I've used before and it's not terrible :)
Though the error message/diff for the string version may be tricky...
Nice! I had not thought of that. I'd even say that between the two options I'd even settle for this supporting this one first. I know a lot of people are not thrilled about writing css as js objects, partly because of the camel case thing.
:tada: This issue has been resolved in version 1.2.0 :tada:
The release is available on:
npm package (@latest dist-tag)Your semantic-release bot :package::rocket:
Most helpful comment
I think it'd be super if it could also accept a string of css:
May need to use https://www.npmjs.com/package/css which I've used before and it's not terrible :)
Though the error message/diff for the string version may be tricky...