Skip to content

Commit

Permalink
Add test for this context
Browse files Browse the repository at this point in the history
  • Loading branch information
poteto committed Sep 14, 2022
1 parent eaa47a7 commit a4af797
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/react-reconciler/src/ReactFiberHooks.new.js
Original file line number Diff line number Diff line change
Expand Up @@ -1879,7 +1879,7 @@ function mountEvent<T>(callback: () => T): () => T {
if (isInvalidExecutionContextForEventFunction()) {
throw new Error('An event from useEvent was called during render.');
}
return ref.current.apply(this, arguments);
return ref.current.apply(undefined, arguments);
}

// TODO: We don't need all the overhead of an effect object since there are no deps and no
Expand Down
2 changes: 1 addition & 1 deletion packages/react-reconciler/src/ReactFiberHooks.old.js
Original file line number Diff line number Diff line change
Expand Up @@ -1879,7 +1879,7 @@ function mountEvent<T>(callback: () => T): () => T {
if (isInvalidExecutionContextForEventFunction()) {
throw new Error('An event from useEvent was called during render.');
}
return ref.current.apply(this, arguments);
return ref.current.apply(undefined, arguments);
}

// TODO: We don't need all the overhead of an effect object since there are no deps and no
Expand Down
46 changes: 46 additions & 0 deletions packages/react-reconciler/src/__tests__/useEvent-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,52 @@ describe('useEvent', () => {
]);
});

// @gate enableUseEventHook
it('does not preserve `this` in event functions', () => {
class GreetButton extends React.PureComponent {
greet = () => {
this.props.onClick();
};
render() {
return <Text text={'Say ' + this.props.hello} />;
}
}
function Greeter({hello}) {
const person = {
toString() {
return 'Jane';
},
greet() {
return updateGreeting(this + ' says ' + hello);
},
};
const [greeting, updateGreeting] = useState('Seb says ' + hello);
const onClick = useEvent(person.greet);

return (
<>
<GreetButton hello={hello} onClick={onClick} ref={button} />
<Text text={'Greeting: ' + greeting} />
</>
);
}

const button = React.createRef(null);
ReactNoop.render(<Greeter hello={'hej'} />);
expect(Scheduler).toFlushAndYield(['Say hej', 'Greeting: Seb says hej']);
expect(ReactNoop.getChildren()).toEqual([
span('Say hej'),
span('Greeting: Seb says hej'),
]);

act(button.current.greet);
expect(Scheduler).toHaveYielded(['Greeting: undefined says hej']);
expect(ReactNoop.getChildren()).toEqual([
span('Say hej'),
span('Greeting: undefined says hej'),
]);
});

// @gate enableUseEventHook
it('throws when called in render', () => {
class IncrementButton extends React.PureComponent {
Expand Down

0 comments on commit a4af797

Please sign in to comment.