Skip to content

Commit

Permalink
added POC event propagation
Browse files Browse the repository at this point in the history
  • Loading branch information
Nuno Campos committed May 7, 2016
1 parent a2a5f12 commit 9c48a80
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/ShallowWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -348,16 +348,21 @@ export default class ShallowWrapper {
* @returns {ShallowWrapper}
*/
simulate(event, mock, ...args) {
const handler = this.prop(propFromEvent(event));
const eventProp = propFromEvent(event);
const e = Object.assign(new SyntheticEvent(undefined, undefined, { type: event }), mock);
if (handler) {
withSetStateAllowed(() => {
// TODO(lmr): create/use synthetic events
// TODO(lmr): emulate React's event propagation
handler(e, ...args);
this.root.update();
});
}
withSetStateAllowed(() => {
let current = this;

do {
const handler = current.prop(eventProp);
if (handler) {
handler(e, ...args);
}
current = current.parent();
} while (!e.isPropagationStopped() && current.node !== undefined);

this.root.update();
});
return this;
}

Expand Down
41 changes: 41 additions & 0 deletions test/ShallowWrapper-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,47 @@ describe('shallow', () => {

});

it('should propagate events', () => {
const innerOnClick = sinon.spy();
const outerOnClick = sinon.spy();
class Foo extends React.Component {
render() {
return (
<div onClick={outerOnClick}>
<a onClick={innerOnClick}>foo</a>
</div>
);
}
}

const wrapper = shallow(<Foo />);

wrapper.find('a').simulate('click');
expect(innerOnClick.calledOnce).to.equal(true);
expect(outerOnClick.calledOnce).to.equal(true);
});

it('should respect event.stopPropagation()', () => {
const innerOnClick = sinon.spy(e => {
e.stopPropagation();
});
const outerOnClick = sinon.spy();
class Foo extends React.Component {
render() {
return (
<div onClick={outerOnClick}>
<a onClick={innerOnClick}>foo</a>
</div>
);
}
}

const wrapper = shallow(<Foo />);

wrapper.find('a').simulate('click');
expect(innerOnClick.calledOnce).to.equal(true);
expect(outerOnClick.calledOnce).to.equal(false);
});

it('should pass in event data', () => {
const spy = sinon.spy();
Expand Down

0 comments on commit 9c48a80

Please sign in to comment.