-
Notifications
You must be signed in to change notification settings - Fork 412
feature: toHaveStyle custom matcher #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2dc785e
feature: toHaveStyle custom matcher
gnapse 2c06821
Fix test coverage
gnapse 81d6605
Use more robust css parser library
gnapse 12994eb
Handle css parsing errors gracefully
gnapse 907642e
Improve how printed out styles look like in failing tests messages
gnapse d4336b7
Add documentation to the README
gnapse 60ae40d
Use redent for indent
gnapse File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -32,7 +32,11 @@ | |
"author": "Ernesto Garcia <[email protected]> (http://gnapse.github.io/)", | ||
"license": "MIT", | ||
"dependencies": { | ||
"jest-matcher-utils": "^22.4.3" | ||
"chalk": "^2.4.1", | ||
"css": "^2.2.3", | ||
"jest-diff": "^22.4.3", | ||
"jest-matcher-utils": "^22.4.3", | ||
"redent": "^2.0.0" | ||
}, | ||
"devDependencies": { | ||
"kcd-scripts": "^0.37.0" | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import {parse} from 'css' | ||
import {matcherHint} from 'jest-matcher-utils' | ||
import jestDiff from 'jest-diff' | ||
import chalk from 'chalk' | ||
import {checkHtmlElement} from './utils' | ||
|
||
function parseCSS(css) { | ||
const ast = parse(`selector { ${css} }`, {silent: true}).stylesheet | ||
if (ast.parsingErrors && ast.parsingErrors.length > 0) { | ||
const {reason, line, column} = ast.parsingErrors[0] | ||
return { | ||
parsingError: `Syntax error parsing expected css: ${reason} in ${line}:${column}`, | ||
} | ||
} | ||
const parsedRules = ast.rules[0].declarations | ||
.filter(d => d.type === 'declaration') | ||
.reduce( | ||
(obj, {property, value}) => Object.assign(obj, {[property]: value}), | ||
{}, | ||
) | ||
return {parsedRules} | ||
} | ||
|
||
function isSubset(styles, computedStyle) { | ||
return Object.entries(styles).every( | ||
([prop, value]) => computedStyle.getPropertyValue(prop) === value, | ||
) | ||
} | ||
|
||
function printoutStyles(styles) { | ||
return Object.keys(styles) | ||
.sort() | ||
.map(prop => `${prop}: ${styles[prop]};`) | ||
.join('\n') | ||
} | ||
|
||
// Highlights only style rules that were expected but were not found in the | ||
// received computed styles | ||
function expectedDiff(expected, computedStyles) { | ||
const received = Array.from(computedStyles) | ||
.filter(prop => expected[prop]) | ||
.reduce( | ||
(obj, prop) => | ||
Object.assign(obj, {[prop]: computedStyles.getPropertyValue(prop)}), | ||
{}, | ||
) | ||
const diffOutput = jestDiff( | ||
printoutStyles(expected), | ||
printoutStyles(received), | ||
) | ||
// Remove the "+ Received" annotation because this is a one-way diff | ||
return diffOutput.replace(`${chalk.red('+ Received')}\n`, '') | ||
} | ||
|
||
export function toHaveStyle(htmlElement, css) { | ||
checkHtmlElement(htmlElement) | ||
const {parsedRules: expected, parsingError} = parseCSS(css) | ||
if (parsingError) { | ||
return { | ||
pass: this.isNot, // Fail regardless of the test being positive or negative | ||
message: () => parsingError, | ||
} | ||
} | ||
const received = getComputedStyle(htmlElement) | ||
return { | ||
pass: isSubset(expected, received), | ||
message: () => { | ||
const matcher = `${this.isNot ? '.not' : ''}.toHaveStyle` | ||
return [ | ||
matcherHint(matcher, 'element', ''), | ||
expectedDiff(expected, received), | ||
].join('\n\n') | ||
}, | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe we could use
css.stringify
to ensure that this handles things like media queries and stuff properly?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I thought about it, but there's a problem with this. The
css
library seems to only be able to handle the syntax of css to the stylesheet level, that is,property: value;
pairs listed inside aselector { ... }
. And here I'm handling only plain css property/value pairs (well, sets of property/value pairs really) abstracted away from a selector. I do not even think media queries apply.For instance, I'd have to convert what
getComputedStyles
give me, which is, again, a set of plain css property/value pairs, and manually build the AST that thecss
lib would have created out of those rules with a fake css selector wrapping them, just to makecss.stringify
be able to process it.I saw the point of using
css
to parse because even though I had to fake wrapping the plain css props in a selector, it gives me syntax error handling, which is amazing for the pretty error messages when expectations in tests fail. But after all this reasoning do you still think is worth usingcss.stringify
@kentcdodds?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(Do we even need to handle media queries here? Maybe I'm missing out some potential great use case for this, but I don't see it yet)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're right, I don't think we need to use
css.stringify
👍