Skip to content

Instantly share code, notes, and snippets.

@morgs32 morgs32/until.js forked from matthieuprat/ README.md
Created Jul 24, 2017

Embed
What would you like to do?
Until operator for Enzyme's shallow wrapper
export default function until(selector, {context} = this.options) {
if (this.isEmptyRender() || typeof this.node.type === 'string')
return this
const instance = this.instance()
if (instance.getChildContext) {
context = {
...context,
...instance.getChildContext(),
}
}
return this.is(selector)
? this.shallow({context})
: this.shallow({context})::until(selector, {context})
}
import React, {PropTypes} from 'react'
import {expect} from 'chai'
import {shallow} from 'enzyme'
import until from 'until'
describe('until', () => {
const Div = () => <div />
const hoc = Component => () => <Component />
it('shallow renders the current wrapper one level deep', () => {
const EnhancedDiv = hoc(Div)
const wrapper = shallow(<EnhancedDiv />)::until('Div')
expect(wrapper).to.contain(<div />)
})
it('shallow renders the current wrapper several levels deep', () => {
const EnhancedDiv = hoc(hoc(hoc(Div)))
const wrapper = shallow(<EnhancedDiv />)::until('Div')
expect(wrapper).to.contain(<div />)
})
it('stops shallow rendering when the wrapper is empty', () => {
const nullHoc = () => () => null
const EnhancedDiv = nullHoc(Div)
const wrapper = shallow(<EnhancedDiv />)::until('Div')
expect(wrapper).to.be.blank()
})
it('shallow renders the current wrapper even if the selector never matches', () => {
const EnhancedDiv = hoc(Div)
const wrapper = shallow(<EnhancedDiv />)::until('NotDiv')
expect(wrapper).to.contain(<div />)
})
it('stops shallow rendering when it encounters a DOM element', () => {
const wrapper = shallow(<div><Div /></div>)::until('Div')
expect(wrapper).to.contain(<div><Div /></div>)
})
describe('with context', () => {
const Foo = () => <Div />
Foo.contextTypes = {quux: PropTypes.bool.isRequired}
class Bar extends React.Component {
static childContextTypes = {quux: PropTypes.bool}
getChildContext = () => ({quux: true})
render = () => <Foo />
}
it('passes down context from the root component', () => {
const EnhancedFoo = hoc(Foo)
const wrapper = shallow(<EnhancedFoo />, {context: {quux: true}})::until('Foo')
expect(wrapper.context('quux')).to.be.true()
expect(wrapper).to.contain(<Div />)
})
it('passes down context from an intermediary component', () => {
const EnhancedBar = hoc(Bar)
const wrapper = shallow(<EnhancedBar />)::until('Foo')
expect(wrapper.context('quux')).to.be.true()
expect(wrapper).to.contain(<Div />)
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.