Skip to content

Commit

Permalink
improve custom toMatchCss matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
RobinMalfait authored and adamwathan committed Aug 28, 2020
1 parent 44dbde8 commit ad7fec4
Showing 1 changed file with 45 additions and 10 deletions.
55 changes: 45 additions & 10 deletions jest/customMatchers.js
@@ -1,3 +1,13 @@
import prettier from 'prettier'
import diff from 'jest-diff'

function format(input) {
return prettier.format(input, {
parser: 'css',
printWidth: 100,
})
}

expect.extend({
// Compare two CSS strings with all whitespace removed
// This is probably naive but it's fast and works well enough.
Expand All @@ -6,16 +16,41 @@ expect.extend({
return str.replace(/\s/g, '').replace(/;/g, '')
}

if (stripped(received) === stripped(argument)) {
return {
message: () => `expected ${received} not to match CSS ${argument}`,
pass: true,
}
} else {
return {
message: () => `expected ${received} to match CSS ${argument}`,
pass: false,
}
const options = {
comment: 'stripped(received) === stripped(argument)',
isNot: this.isNot,
promise: this.promise,
}

const pass = stripped(received) === stripped(argument)

const message = pass
? () => {
return (
this.utils.matcherHint('toMatchCss', undefined, undefined, options) +
'\n\n' +
`Expected: not ${this.utils.printExpected(format(received))}\n` +
`Received: ${this.utils.printReceived(format(argument))}`
)
}
: () => {
const actual = format(received)
const expected = format(argument)

const diffString = diff(expected, actual, {
expand: this.expand,
})

return (
this.utils.matcherHint('toMatchCss', undefined, undefined, options) +
'\n\n' +
(diffString && diffString.includes('- Expect')
? `Difference:\n\n${diffString}`
: `Expected: ${this.utils.printExpected(expected)}\n` +
`Received: ${this.utils.printReceived(actual)}`)
)
}

return { actual: received, message, pass }
},
})

0 comments on commit ad7fec4

Please sign in to comment.