Skip to content

Instantly share code, notes, and snippets.

@nphmuller
Last active March 7, 2023 20:32
Show Gist options
  • Save nphmuller/c3f3ffe44f7a21f9b98b9539ed0f72b7 to your computer and use it in GitHub Desktop.
Save nphmuller/c3f3ffe44f7a21f9b98b9539ed0f72b7 to your computer and use it in GitHub Desktop.
Custom Jest matcher that matches MUI X 6 date picker values. Based on https://github.com/mui/mui-x/blob/97220aaf2964a9dcd08d6a2a263f4f1610d71a75/test/utils/pickers-utils.tsx#L319
export function toHaveDateValue(this: jest.MatcherContext, input: HTMLInputElement, expectedDate: Date) {
const normalizedInputValue = input.value
.replace(/\u200e|\u2066|\u2067|\u2068|\u2069/g, '')
.replace(/ \/ /g, '/')
const actualDate = new Date(normalizedInputValue)
return {
pass: actualDate.getTime() === expectedDate.getTime(),
message: () => {
const to = this.isNot ? 'not to' : 'to'
return getMessage(
this.utils.matcherHint(`${this.isNot ? '.not' : ''}.toHaveInputDateValue`),
`Expected date input ${to} have value`,
expectedDate,
'Received',
actualDate
)
}
}
}
function getMessage(matcher: string, expectedLabel: string, expectedValue: any, receivedLabel: string, receivedValue: any) {
return [
`${matcher}\n`,
`${expectedLabel}:\n${EXPECTED_COLOR(redent(display(expectedValue), 2))}`,
`${receivedLabel}:\n${RECEIVED_COLOR(redent(display(receivedValue), 2))}`
].join('\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment