From 230c8528118d698845579f4f3980afb2d8c95393 Mon Sep 17 00:00:00 2001 From: Jovi De Croock Date: Mon, 29 Jan 2024 12:09:57 +0100 Subject: [PATCH] support passing context into pure component --- compat/src/PureComponent.js | 3 ++- compat/test/browser/PureComponent.test.js | 32 +++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/compat/src/PureComponent.js b/compat/src/PureComponent.js index 0d08f7a9c2..380aeb037f 100644 --- a/compat/src/PureComponent.js +++ b/compat/src/PureComponent.js @@ -4,8 +4,9 @@ import { shallowDiffers } from './util'; /** * Component class with a predefined `shouldComponentUpdate` implementation */ -export function PureComponent(p) { +export function PureComponent(p, c) { this.props = p; + this.context = c; } PureComponent.prototype = new Component(); // Some third-party libraries check if this property is present diff --git a/compat/test/browser/PureComponent.test.js b/compat/test/browser/PureComponent.test.js index c24113ca49..ee75ed7197 100644 --- a/compat/test/browser/PureComponent.test.js +++ b/compat/test/browser/PureComponent.test.js @@ -37,6 +37,38 @@ describe('PureComponent', () => { expect(spy).to.be.calledWithMatch(expected, expected); }); + it('should pass context in constructor', () => { + let instance; + // Not initializing state matches React behavior: https://codesandbox.io/s/rml19v8o2q + class Foo extends React.PureComponent { + constructor(props, context) { + super(props, context); + expect(this.props).to.equal(props); + expect(this.state).to.deep.equal(undefined); + expect(this.context).to.equal(context); + + instance = this; + } + render(props) { + return
Hello
; + } + } + + sinon.spy(Foo.prototype, 'render'); + + const PROPS = { foo: 'bar' }; + React.render(, scratch); + + expect(Foo.prototype.render) + .to.have.been.calledOnce.and.to.have.been.calledWithMatch(PROPS, {}, {}) + .and.to.have.returned(sinon.match({ type: 'div', props: PROPS })); + expect(instance.props).to.deep.equal(PROPS); + expect(instance.state).to.deep.equal({}); + expect(instance.context).to.deep.equal({}); + + expect(scratch.innerHTML).to.equal('
Hello
'); + }); + it('should ignore the __source variable', () => { const pureSpy = sinon.spy(); const appSpy = sinon.spy();