ant-design/components/config-provider/__tests__/memo.test.js

82 lines
2.6 KiB
JavaScript
Raw Normal View History

2021-01-12 21:02:53 +08:00
import React, { useState } from 'react';
import { mount } from 'enzyme';
import ConfigProvider from '..';
import { ConfigConsumer } from '../context';
// https://github.com/ant-design/ant-design/issues/27617
describe('ConfigProvider', () => {
const RenderCounter = ({ config }) => {
const [count, setCount] = React.useState(0);
React.useEffect(() => setCount(c => c + 1), [config]);
return <div id="counter">{count}</div>;
};
const Sibling = () => (
<ConfigConsumer>{config => <RenderCounter config={config} />}</ConfigConsumer>
);
2021-01-12 21:02:53 +08:00
it('should not generate new context config when render', () => {
const MemoedSibling = React.memo(Sibling);
const App = () => {
2021-01-12 21:02:53 +08:00
const [pageHeader, setPageHeader] = useState({ ghost: true });
const [, forceRender] = React.useReducer(v => v + 1, 1);
return (
2021-01-12 21:02:53 +08:00
<ConfigProvider pageHeader={pageHeader}>
<button type="button" className="render" onClick={() => forceRender()}>
Force Render
</button>
<button
type="button"
2021-01-12 21:02:53 +08:00
className="setState"
onClick={() => setPageHeader({ ghost: false })}
>
2021-01-12 21:02:53 +08:00
Change Config
</button>
<MemoedSibling />
</ConfigProvider>
);
};
const wrapper = mount(<App />);
2021-01-12 21:02:53 +08:00
wrapper.find('.render').simulate('click');
expect(wrapper.find('#counter').text()).toEqual('1');
2021-01-12 21:02:53 +08:00
wrapper.find('.setState').simulate('click');
expect(wrapper.find('#counter').text()).toEqual('2');
});
2021-01-12 21:02:53 +08:00
it('should not generate new context config in nested ConfigProvider when render', () => {
const MemoedSibling = React.memo(Sibling);
const App = () => {
2021-01-12 21:02:53 +08:00
const [pageHeader, setPageHeader] = useState({ ghost: true });
const [, forceRender] = React.useReducer(v => v + 1, 1);
2021-01-12 21:02:53 +08:00
return (
2021-01-12 21:02:53 +08:00
<ConfigProvider pageHeader={pageHeader}>
<ConfigProvider>
2021-01-12 21:02:53 +08:00
<button type="button" className="render" onClick={() => forceRender()}>
Force Render
</button>
<button
type="button"
2021-01-12 21:02:53 +08:00
className="setState"
onClick={() => setPageHeader({ ghost: false })}
>
2021-01-12 21:02:53 +08:00
Change Config
</button>
<MemoedSibling />
</ConfigProvider>
</ConfigProvider>
);
};
const wrapper = mount(<App />);
2021-01-12 21:02:53 +08:00
wrapper.find('.render').simulate('click');
expect(wrapper.find('#counter').text()).toEqual('1');
2021-01-12 21:02:53 +08:00
wrapper.find('.setState').simulate('click');
expect(wrapper.find('#counter').text()).toEqual('2');
});
});