Skip to content

Commit ebb36e9

Browse files
committed
test: test driven
1 parent dfe3484 commit ebb36e9

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

src/Immutable.tsx

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,13 @@ export function makeImmutable<T extends React.ComponentType<any>>(Component: T):
3434
* Wrapped Component with `React.memo`.
3535
* But will rerender when parent with `makeImmutable` rerender.
3636
*/
37-
export function responseImmutable<T extends React.ComponentType<any>>(Component: T): T {
37+
export function responseImmutable<T extends React.ComponentType<any>>(
38+
Component: T,
39+
propsAreEqual?: (
40+
prevProps: Readonly<React.ComponentProps<T>>,
41+
nextProps: Readonly<React.ComponentProps<T>>,
42+
) => boolean,
43+
): T {
3844
const refAble = supportRef(Component);
3945

4046
const ImmutableComponent = function (props: any, ref: any) {
@@ -51,6 +57,6 @@ export function responseImmutable<T extends React.ComponentType<any>>(Component:
5157
}
5258

5359
return refAble
54-
? React.memo(React.forwardRef(ImmutableComponent))
55-
: (React.memo(ImmutableComponent) as any);
60+
? React.memo(React.forwardRef(ImmutableComponent), propsAreEqual)
61+
: (React.memo(ImmutableComponent, propsAreEqual) as any);
5662
}

tests/immutable.test.tsx

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,27 @@ describe('Immutable', () => {
9595
expect(rootRef.current).toBe(container.querySelector('.root'));
9696
expect(rawRef.current).toBe(container.querySelector('.raw'));
9797
});
98+
99+
it('customize propsAreEqual', () => {
100+
const Input: React.FC<{
101+
value: string;
102+
onChange: React.ChangeEventHandler<HTMLInputElement>;
103+
}> = props => (
104+
<>
105+
<input {...props} />
106+
<RenderTimer id="input" />
107+
</>
108+
);
109+
110+
const ImmutableInput = responseImmutable(Input);
111+
112+
const { container, rerender } = render(<ImmutableInput value="same" onChange={() => {}} />);
113+
expect(container.querySelector('#input').textContent).toEqual('1');
114+
115+
rerender(<ImmutableInput value="same" onChange={() => {}} />);
116+
expect(container.querySelector('#input').textContent).toEqual('1');
117+
118+
rerender(<ImmutableInput value="not-same" onChange={() => {}} />);
119+
expect(container.querySelector('#input').textContent).toEqual('2');
120+
});
98121
});

0 commit comments

Comments
 (0)