Skip to content

Instantly share code, notes, and snippets.

@AlexJukes
Created March 7, 2023 16:15
Show Gist options
  • Select an option

  • Save AlexJukes/6318a2a23b7a7c63b2969000242b2a77 to your computer and use it in GitHub Desktop.

Select an option

Save AlexJukes/6318a2a23b7a7c63b2969000242b2a77 to your computer and use it in GitHub Desktop.
A custom jest matcher for checking whether props have been passed to a mocked React component
expect.extend({
toReceivePropsContaining(received, expected) {
if (!received._isMockFunction) {
return {
message: () =>
`Expected: ${chalk.green(
'[A mocked React component]'
)}\nReceived: ${this.utils.printReceived(received)}`,
pass: false,
}
}
// we check the props given at the latest invocation of the mocked component
const [props] = received.mock.calls.at(-1)
const pass = this.equals(props, expect.objectContaining({ ...expected }))
if (pass) {
return {
message: () =>
`Expected: ${this.utils.printExpected(
expected
)}\nReceived: ${this.utils.printReceived(received)}`,
pass: true,
}
}
return {
message: () =>
`Expected props to contain: ${this.utils.printExpected(
expected
)}\nReceived props: ${this.utils.printReceived(props)}`,
pass: false,
}
},
})
/*
==========
Example Usage
==========
// Component.ts
const Component: React.FC = () => (<SubComponent isCool={true} />)
// Component.spec.ts
import { Component } from './component'
import { SubComponent } from './component/sub-component'
jest.mock('./component/sub-component')
it('is a test', () => {
render(<Component />)
expect(SubComponent).toReceivePropsContaining({ isCool: true })
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment