Skip to content

Instantly share code, notes, and snippets.

@nufaylr
Forked from evansiroky/icon.js
Created November 26, 2019 08:42
Show Gist options
  • Save nufaylr/b7d29f8fe39d70006ec5c149fd78c29b to your computer and use it in GitHub Desktop.
Save nufaylr/b7d29f8fe39d70006ec5c149fd78c29b to your computer and use it in GitHub Desktop.
Mocking children components with Jest - does this make sense?
import React from 'react'
export default class Icon extends React.Component {
render () {
const {type, className} = this.props
return (
<i
className={`fa fa-${type} fa-fw ${className}`}
{...this.props}
/>
)
}
}
/* global describe, it, expect */
import React from 'react'
import renderer from 'react-test-renderer'
import Icon from '../../lib/components/icon'
describe('Icon', () => {
it('renders correctly', () => {
const tree = renderer.create(
<Icon
type='pencil'
className='test'
/>
).toJSON()
expect(tree).toMatchSnapshot()
})
})
import React from 'react'
import Icon from './icon'
export default class Project extends React.Component {
render () {
const {children} = this.props
return (
<div>
<div
className='ProjectTitle'
>
<Icon type='list' />
<a href='#'>A Link</a>
</div>
{children}
</div>
)
}
}
import React from 'react'
import renderer from 'react-test-renderer'
import { mockComponent } from '../../testUtils'
jest.mock('../../lib/components/icon', () => { return mockComponent('Icon') })
import Project from '../../lib/components/project'
describe('Project', () => {
it('renders correctly', () => {
const tree = renderer.create(
<Project/>
).toJSON()
expect(tree).toMatchSnapshot()
})
})
import React from 'react'
export function mockComponent (componentName) {
return (props) => {
return (
<mocked originalComponent={componentName} {...props}>{props.children}</mocked>
)
}
}
export function mockNamedComponents (componentNames) {
const mockedComponents = {}
for (let i = 0; i < componentNames.length; i++) {
const name = componentNames[i]
mockedComponents[name] = mockComponent(name)
}
return mockedComponents
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment