Skip to content

Instantly share code, notes, and snippets.

@evansiroky
Created September 27, 2016 00:57
Show Gist options
  • Save evansiroky/89deb7759ae487abb5fed6d1dfdfce84 to your computer and use it in GitHub Desktop.
Save evansiroky/89deb7759ae487abb5fed6d1dfdfce84 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
}
@smartsatheesh
Copy link

TypeError: Cannot read property 'mockComponent' of undefined

@Shailender-JFT
Copy link

how we can write test cases for the child component if we use above child mocking example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment