Skip to content

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock committed Dec 31, 2024
1 parent 8d7f867 commit d310b3a
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/create-context.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { enqueueRender } from './component';
export let i = 0;

export function createContext(defaultValue) {
/** @type {import('./internal').FunctionComponent} */
function Context(props) {
if (!this.getChildContext) {
/** @type {Set<import('./internal').Component> | null} */
Expand All @@ -18,6 +17,7 @@ export function createContext(defaultValue) {
};

this.shouldComponentUpdate = function (_props) {
// @ts-expect-error even
if (this.props.value !== _props.value) {
subs.forEach(c => {
c._force = true;
Expand Down
34 changes: 34 additions & 0 deletions test/browser/createContext.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,40 @@ describe('createContext', () => {
expect(scratch.innerHTML).to.equal('<div><div>a</div></div>');
});

it('should pass context to a consumer (non-provider)', () => {
const Ctx = createContext(null);
const CONTEXT = { a: 'a' };

let receivedContext;

class Inner extends Component {
render(props) {
return <div>{props.a}</div>;
}
}

sinon.spy(Inner.prototype, 'render');

render(
<Ctx value={CONTEXT}>
<div>
<Ctx.Consumer>
{data => {
receivedContext = data;
return <Inner {...data} />;
}}
</Ctx.Consumer>
</div>
</Ctx>,
scratch
);

// initial render does not invoke anything but render():
expect(Inner.prototype.render).to.have.been.calledWithMatch(CONTEXT);
expect(receivedContext).to.equal(CONTEXT);
expect(scratch.innerHTML).to.equal('<div><div>a</div></div>');
});

// This optimization helps
// to prevent a Provider from rerendering the children, this means
// we only propagate to children.
Expand Down
17 changes: 17 additions & 0 deletions test/ts/custom-elements.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,20 @@ class SimpleComponent extends Component {
}

const component = <SimpleComponent />;
class SimpleComponentWithContextAsProvider extends Component {
componentProp = 'componentProp';
render() {
// Render inside div to ensure standard JSX elements still work
return (
<Ctx value={{ contextValue: 'value' }}>
<div>
{/* Ensure context still works */}
<Ctx.Consumer>
{({ contextValue }) => contextValue.toLowerCase()}
</Ctx.Consumer>
</div>
</Ctx>
);
}
}
const component2 = <SimpleComponentWithContextAsProvider />;

0 comments on commit d310b3a

Please sign in to comment.