|
| 1 | +import React from 'react'; |
| 2 | +import { expect } from 'chai'; |
| 3 | +import sinon from 'sinon-sandbox'; |
| 4 | + |
| 5 | +export default function describeInvoke({ |
| 6 | + Wrap, |
| 7 | + WrapperName, |
| 8 | +}) { |
| 9 | + describe('.invoke(propName)(..args)', () => { |
| 10 | + class CounterButton extends React.Component { |
| 11 | + constructor(props) { |
| 12 | + super(props); |
| 13 | + this.state = { count: 0 }; |
| 14 | + } |
| 15 | + |
| 16 | + render() { |
| 17 | + const { count } = this.state; |
| 18 | + return ( |
| 19 | + <div> |
| 20 | + <button |
| 21 | + type="button" |
| 22 | + onClick={() => this.setState(({ count: oldCount }) => ({ count: oldCount + 1 }))} |
| 23 | + > |
| 24 | + {count} |
| 25 | + </button> |
| 26 | + </div> |
| 27 | + ); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + class ClickableLink extends React.Component { |
| 32 | + render() { |
| 33 | + const { onClick } = this.props; |
| 34 | + return ( |
| 35 | + <div> |
| 36 | + <a onClick={onClick}>foo</a> |
| 37 | + </div> |
| 38 | + ); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + it('throws when pointing to a non-function prop', () => { |
| 43 | + const wrapper = Wrap(<div data-a={{}} />); |
| 44 | + |
| 45 | + expect(() => wrapper.invoke('data-a')).to.throw( |
| 46 | + TypeError, |
| 47 | + `${WrapperName}::invoke() requires the name of a prop whose value is a function`, |
| 48 | + ); |
| 49 | + |
| 50 | + expect(() => wrapper.invoke('does not exist')).to.throw( |
| 51 | + TypeError, |
| 52 | + `${WrapperName}::invoke() requires the name of a prop whose value is a function`, |
| 53 | + ); |
| 54 | + }); |
| 55 | + |
| 56 | + it('can update the state value', () => { |
| 57 | + const wrapper = Wrap(<CounterButton />); |
| 58 | + expect(wrapper.state('count')).to.equal(0); |
| 59 | + wrapper.find('button').invoke('onClick')(); |
| 60 | + expect(wrapper.state('count')).to.equal(1); |
| 61 | + }); |
| 62 | + |
| 63 | + it('can return the handlers’ return value', () => { |
| 64 | + const sentinel = {}; |
| 65 | + const spy = sinon.stub().returns(sentinel); |
| 66 | + |
| 67 | + const wrapper = Wrap(<ClickableLink onClick={spy} />); |
| 68 | + |
| 69 | + const value = wrapper.find('a').invoke('onClick')(); |
| 70 | + expect(value).to.equal(sentinel); |
| 71 | + expect(spy).to.have.property('callCount', 1); |
| 72 | + }); |
| 73 | + |
| 74 | + it('can pass in arguments', () => { |
| 75 | + const spy = sinon.spy(); |
| 76 | + |
| 77 | + const wrapper = Wrap(<ClickableLink onClick={spy} />); |
| 78 | + |
| 79 | + const a = {}; |
| 80 | + const b = {}; |
| 81 | + wrapper.find('a').invoke('onClick')(a, b); |
| 82 | + expect(spy).to.have.property('callCount', 1); |
| 83 | + const [[arg1, arg2]] = spy.args; |
| 84 | + expect(arg1).to.equal(a); |
| 85 | + expect(arg2).to.equal(b); |
| 86 | + }); |
| 87 | + }); |
| 88 | +} |
0 commit comments