| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182 |
- import BaseTable from '../Table';
- import Table from '../index';
- import Column from '../Column';
- import {Tag, Tooltip} from '../../index';
- import {
- getColumns,
- getData,
- getGroupColumns,
- getGroupData,
- getJSXColumns,
- getNestColumns,
- getNestData,
- getRandomNumber,
- getTreeData,
- mount,
- sleep,
- } from '../../_test_/utils';
- import {BASE_CLASS_PREFIX} from '../../../semi-foundation/base/constants';
- import {IconStar} from '@douyinfe/semi-icons';
- /**
- * Table 需要测试的使用场景
- * ✅ JSX 写法
- * ✅ 行选择
- * ✅ 分页
- * ✅ 固定列
- * ✅ 排序
- * ✅ 筛选
- * ✅ 展开
- * ✅ 树形展示
- * ✅ 自定义行或单元格
- * ✅ 分组
- * ✅ 表头合并
- * ✅ 更新数据
- * ✅ 完全自定义渲染
- * ✅ 行列合并
- * ❌ 可伸缩列(不好测试)
- * ❌ 拖拽排序(不好测试)
- * ❌ 虚拟化
- */
- const dataTotalSize = 46;
- const data = getData(dataTotalSize);
- const columns = getColumns();
- function testAppearance(demo, params) {
- const {onRow, myCls, myClsIndex} = params; // check table wrapper
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-wrapper`).length).toBe(1); // check if has header
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-title`).length).toBe(1); // check if has footer
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-footer`).length).toBe(1); // check onRow
- expect(onRow.called).toBe(true);
- expect(
- demo
- .find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row`)
- .at(0)
- .hasClass(myCls)
- ).toBe(false);
- expect(
- demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row`).reduce((prev, item, index) => {
- if (item.hasClass(myCls)) {
- return index;
- } else {
- return prev;
- }
- }, -1)
- ).toBe(myClsIndex); // check pagination
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-pagination-outer`).length).toBe(1); // click page 2
- const curPage = 2;
- demo.find(`.${BASE_CLASS_PREFIX}-page li`)
- .at(curPage)
- .simulate('click');
- expect(demo.find(BaseTable).state('pagination')).toHaveProperty('currentPage', curPage);
- }
- describe(`Table`, () => {
- it(`test jsx columns appearance`, async () => {
- const myCls = `my-tr-class`;
- const myClsIndex = 2;
- const onRow = sinon.spy((record, index) => ({
- className: index === myClsIndex ? myCls : '',
- }));
- const columns = getJSXColumns();
- const demo = mount(
- <Table
- dataSource={data}
- onRow={onRow}
- title={() => 'Table Title'}
- footer={() => 'Table Footer'}
- children={columns}
- />
- );
- testAppearance(demo, {
- onRow,
- myCls,
- myClsIndex,
- });
- const newColumns = getJSXColumns();
- demo.setProps({
- children: newColumns,
- });
- testAppearance(demo, {
- onRow,
- myCls,
- myClsIndex,
- });
- demo.unmount();
- });
- it(`test object columns appearance`, async () => {
- const myCls = `my-tr-class`;
- const myClsIndex = 2;
- const onRow = sinon.spy((record, index) => ({
- className: index === myClsIndex ? myCls : '',
- }));
- const columns = getColumns();
- const demo = mount(
- <Table
- dataSource={data}
- onRow={onRow}
- title={() => 'Table Title'}
- footer={() => 'Table Footer'}
- columns={columns}
- />
- );
- testAppearance(demo, {
- onRow,
- myCls,
- myClsIndex,
- });
- const newColumns = getColumns();
- demo.setProps({
- columns: newColumns,
- });
- testAppearance(demo, {
- onRow,
- myCls,
- myClsIndex,
- });
- });
- it(`test dataSource change appearance`, async () => {
- const myCls = `my-tr-class`;
- const myClsIndex = 2;
- const onRow = sinon.spy((record, index) => ({
- className: index === myClsIndex ? myCls : '',
- }));
- const columns = getColumns();
- const data = getData(25);
- const demo = mount(
- <Table
- dataSource={data}
- onRow={onRow}
- title={() => 'Table Title'}
- footer={() => 'Table Footer'}
- columns={columns}
- />
- );
- testAppearance(demo, {
- onRow,
- myCls,
- myClsIndex,
- });
- const dataNum = getRandomNumber(100, 40);
- const newData = getData(dataNum);
- demo.setProps({
- dataSource: newData,
- });
- testAppearance(demo, {
- onRow,
- myCls,
- myClsIndex,
- });
- });
- it(`test selection`, async () => {
- const columns = getColumns();
- const selectedRowKeys = ['0'];
- const rowKey = 'key';
- const disabledKeys = ['4'];
- let rowSelection = {
- onChange: sinon.spy((selectedRowKeys, selectedRows) => {
- rowSelection = {...rowSelection, selectedRowKeys: [...selectedRowKeys]};
- demo.setProps({
- rowSelection,
- });
- }),
- onSelectAll: sinon.spy((selected, selectedRows, changedRows) => {
- rowSelection = {...rowSelection, selectedRowKeys: selected ? [...selectedRowKeys] : []};
- demo.setProps({
- rowSelection,
- });
- }),
- getCheckboxProps: sinon.spy(record => ({
- disabled: disabledKeys.includes(record[rowKey]),
- // Column configuration not to be checked
- name: record.name,
- })),
- onSelect: sinon.spy((record, selected) => {
- }),
- selectedRowKeys: ['3'],
- defaultSelectedRowKeys: ['0', '1'],
- };
- const demo = mount(<Table rowKey={rowKey} dataSource={data} columns={columns} rowSelection={rowSelection}/>);
- expect(demo.find(`.${BASE_CLASS_PREFIX}-checkbox`).length).toBeGreaterThan(0);
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-row .${BASE_CLASS_PREFIX}-checkbox-inner-checked`).length).toBe(
- rowSelection.selectedRowKeys.length
- );
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-checkbox-indeterminate`).length).toBe(
- 1
- );
- expect(
- demo
- .find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-checkbox`)
- .map(el => el)
- .every((el, index) =>
- disabledKeys.includes(index.toString())
- ? el.hasClass(`${BASE_CLASS_PREFIX}-checkbox-disabled`)
- : true
- )
- ).toBeTruthy(); // click disabled checkbox
- demo.find(`.${BASE_CLASS_PREFIX}-table-row .${BASE_CLASS_PREFIX}-checkbox-disabled`).simulate('click');
- expect(rowSelection.onSelect.notCalled).toBeTruthy(); // click first row checkbox
- demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row .${BASE_CLASS_PREFIX}-checkbox`)
- .at(0)
- .simulate('click');
- expect(rowSelection.onSelect.calledOnce).toBeTruthy(); // click table header checkbox and select all
- demo.find(
- `.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-selection .${BASE_CLASS_PREFIX}-checkbox`
- ).simulate('click');
- expect(rowSelection.onSelectAll.calledOnce).toBeTruthy();
- expect(demo.find(BaseTable).state('rowSelection')).toHaveProperty(
- 'selectedRowKeys',
- rowSelection.selectedRowKeys
- );
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-checkbox-inner-checked`).length).toBe(
- 1
- ); // click table header checkbox and deselect all
- demo.find(
- `.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-selection .${BASE_CLASS_PREFIX}-checkbox`
- ).simulate('click');
- expect(rowSelection.onSelectAll.calledTwice).toBeTruthy();
- expect(demo.find(BaseTable).state('rowSelection')).toHaveProperty('selectedRowKeys', []);
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-checkbox-inner-checked`).length).toBe(
- 0
- );
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-checkbox-indeterminate`).length).toBe(
- 0
- );
- });
- it(`test selection after data change`, async () => {
- const columns = getColumns();
- const selectedRowKeys = ['0'];
- const rowKey = 'key';
- const disabledKeys = ['4'];
- let rowSelection = {
- onSelectAll: sinon.spy((selected, selectedRows, changedRows) => {
- rowSelection = {...rowSelection, selectedRowKeys: selected ? [...selectedRowKeys] : []};
- demo.setProps({
- rowSelection,
- });
- }),
- getCheckboxProps: sinon.spy(record => ({
- disabled: disabledKeys.includes(record[rowKey]),
- // Column configuration not to be checked
- name: record.name,
- })),
- onSelect: sinon.spy((record, selected) => {
- }),
- };
- const demo = mount(<Table rowKey={rowKey} dataSource={data} columns={columns} rowSelection={rowSelection}/>);
- const newData = getData(50);
- demo.setProps({
- dataSource: newData,
- }); // click disabled checkbox
- demo.find(`.${BASE_CLASS_PREFIX}-table-row .${BASE_CLASS_PREFIX}-checkbox-disabled`).simulate('click');
- expect(rowSelection.onSelect.notCalled).toBeTruthy(); // click first row checkbox
- demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row .${BASE_CLASS_PREFIX}-checkbox`)
- .at(0)
- .simulate('click');
- expect(rowSelection.onSelect.calledOnce).toBeTruthy(); // click table header checkbox and select all
- demo.find(
- `.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-selection .${BASE_CLASS_PREFIX}-checkbox`
- ).simulate('click');
- expect(rowSelection.onSelectAll.calledOnce).toBeTruthy(); // click table header checkbox and deselect all
- demo.find(
- `.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-selection .${BASE_CLASS_PREFIX}-checkbox`
- ).simulate('click');
- expect(rowSelection.onSelectAll.calledTwice).toBeTruthy();
- });
- it(`test expandedRowRender and fixed`, async () => {
- const columns = getColumns();
- const rowKey = 'key';
- const expandedRowRender = (record, index, expanded) => (
- <article
- style={{
- margin: 0,
- }}
- >
- <p>{record.description}</p>
- </article>
- );
- const unexpandableKey = '2';
- const demo = mount(
- <Table
- scroll={{
- x: '160%',
- y: 320,
- }}
- defaultExpandAllRows
- rowKey={rowKey}
- expandedRowRender={expandedRowRender}
- hideExpandedColumn={false}
- expandCellFixed={true}
- dataSource={data}
- columns={columns}
- rowExpandable={record => record[rowKey] !== unexpandableKey}
- />
- );
- const leftFixedCells = demo.find(`.${BASE_CLASS_PREFIX}-table-cell-fixed-left`);
- const rightFixedCells = demo.find(`.${BASE_CLASS_PREFIX}-table-cell-fixed-right`);
- expect(leftFixedCells.length).toBeGreaterThan(0);
- expect(rightFixedCells.length).toBeGreaterThan(0);
- expect(
- demo.find(`.${BASE_CLASS_PREFIX}-table-cell-fixed-left.${BASE_CLASS_PREFIX}-table-column-expand`).length
- ).toBeGreaterThan(0);
- const newData = getData(50);
- demo.setProps({
- dataSource: newData,
- });
- expect(
- demo.find(`.${BASE_CLASS_PREFIX}-table-cell-fixed-left.${BASE_CLASS_PREFIX}-table-column-expand`).length
- ).toBeGreaterThan(0);
- });
- it(`test tree data`, async () => {
- const rowKey = 'key';
- const childrenRecordName = 'children';
- const childrenData = getTreeData();
- let expandedRowKeys = [1];
- const onExpand = sinon.spy((expanded, record) => {
- const keySet = new Set([...expandedRowKeys]);
- if (expanded) {
- keySet.add(record[rowKey]);
- } else {
- keySet.delete(record[rowKey]);
- }
- expandedRowKeys = Array.from(keySet);
- demo.setProps({
- expandedRowKeys,
- });
- });
- const demo = mount(
- <Table
- rowKey={rowKey}
- childrenRecordName={childrenRecordName}
- expandedRowKeys={expandedRowKeys}
- columns={columns}
- dataSource={childrenData}
- onExpand={onExpand}
- />
- );
- const table = demo.find(BaseTable);
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row`).length).toBe(
- childrenData[0].children.length + childrenData.length
- ); // click 3rd row to expand row
- table
- .find(
- `.${BASE_CLASS_PREFIX}-table-body .${BASE_CLASS_PREFIX}-table-row .${BASE_CLASS_PREFIX}-table-expand-icon`
- )
- .at(1)
- .simulate('click');
- expect(onExpand.calledOnce).toBeTruthy();
- expect(table.state(`expandedRowKeys`)).toEqual(expandedRowKeys); // click first expand button to collapse row
- table
- .find(
- `.${BASE_CLASS_PREFIX}-table-body .${BASE_CLASS_PREFIX}-table-row .${BASE_CLASS_PREFIX}-table-expand-icon`
- )
- .at(0)
- .simulate('click');
- expect(table.state('expandedRowKeys')).toEqual(expandedRowKeys);
- });
- it(`test grouped data`, async () => {
- const rowKey = record =>
- `${record.city && record.city.toLowerCase()}-${record.job && record.job.toLowerCase()}`;
- const data = [
- {
- city: 'Beijing',
- job: 'FE',
- department: 'IES',
- },
- {
- city: 'Beijing',
- job: 'BE',
- department: 'IES',
- },
- {
- city: 'Shanghai',
- job: 'Android',
- department: 'IES',
- },
- {
- city: 'Tokyo',
- job: 'Android',
- department: 'IES',
- },
- {
- city: 'Shanghai',
- job: 'IOS',
- department: 'EE',
- },
- {
- city: 'LA',
- job: 'SE',
- department: 'EE',
- },
- {
- city: 'Beijing',
- job: 'Android',
- department: 'EE',
- },
- {
- city: 'Tokyo',
- job: 'IOS',
- department: 'EE',
- },
- {
- city: 'Tokyo',
- job: 'SE',
- department: 'DATA',
- },
- {
- city: 'Shanghai',
- job: 'BE',
- department: 'DATA',
- },
- {
- city: 'LA',
- job: 'Android',
- department: 'DATA',
- },
- {
- city: 'LA',
- job: 'IOS',
- department: 'DATA',
- },
- ];
- const columns = [
- {
- dataIndex: 'city',
- title: 'City',
- width: 400,
- sorter: (a, b) => (a.city > b.city ? 1 : -1),
- },
- {
- dataIndex: 'job',
- title: 'Job',
- width: 200,
- filters: [
- {
- text: 'IOS',
- value: 'IOS',
- },
- {
- text: 'Android',
- value: 'Android',
- },
- ],
- onFilter: (value, record) => record.job && record.job.indexOf(value) === 0,
- },
- {
- dataIndex: 'department',
- title: 'Department',
- },
- ];
- const groupedRowClick = sinon.spy();
- const demo = mount(
- <Table
- dataSource={data}
- rowKey={rowKey}
- groupBy={'city'}
- columns={columns}
- renderGroupSection={groupKey => <strong>Jobs in {groupKey}:</strong>}
- onGroupedRow={(group, index) => ({
- onClick: groupedRowClick,
- })}
- clickGroupedRowToExpand
- scroll={{
- y: 480,
- }}
- />
- );
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-row-section`).length).toBe(4);
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-body .${BASE_CLASS_PREFIX}-table-row`).length).toBe(0);
- demo.find(`.${BASE_CLASS_PREFIX}-table-row-section`)
- .at(0)
- .simulate('click');
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-row`).length).toBeGreaterThan(0);
- });
- it(`test events: page, filter, sort`, async () => {
- const columns = [
- {
- title: 'Name',
- dataIndex: 'name',
- width: 150,
- filters: [
- {
- text: '名字包含"1"',
- value: '1',
- },
- {
- text: '名字包含"2"',
- value: '2',
- },
- ],
- onFilter: (value, record) => record.name.indexOf(value) > -1,
- },
- {
- title: 'Age',
- dataIndex: 'age',
- width: 150,
- sorter: (a, b) => (a.age - b.age > 0 ? 1 : -1),
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- {
- render: (text, record) => (
- <Tooltip content={record.description}>
- <Tag color="green">Show Info</Tag>
- </Tooltip>
- ),
- width: 150,
- },
- ];
- let onChangeCalledCount = 0;
- const onChange = sinon.spy();
- const demo = mount(<Table dataSource={data} columns={columns} onChange={onChange}/>);
- demo.find(`.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-filter`).simulate('click');
- expect(demo.find(`.${BASE_CLASS_PREFIX}-dropdown`).length).toBe(1);
- expect(onChange.callCount).toBe(onChangeCalledCount); // click first filter
- demo.find(`.${BASE_CLASS_PREFIX}-dropdown .${BASE_CLASS_PREFIX}-dropdown-item`)
- .at(0)
- .find(`.${BASE_CLASS_PREFIX}-checkbox`)
- .simulate('mousedown', {
- nativeEvent: null,
- });
- expect(onChange.callCount).toBe(++onChangeCalledCount); // click first filter again
- demo.find(`.${BASE_CLASS_PREFIX}-dropdown .${BASE_CLASS_PREFIX}-dropdown-item`)
- .at(0)
- .find(`.${BASE_CLASS_PREFIX}-checkbox`)
- .simulate('mousedown', {
- nativeEvent: null,
- });
- expect(onChange.callCount).toBe(++onChangeCalledCount); // to page 2
- demo.find(`.${BASE_CLASS_PREFIX}-page .${BASE_CLASS_PREFIX}-page-item`)
- .at(2)
- .simulate('click', {
- nativeEvent: null,
- });
- expect(onChange.callCount).toBe(++onChangeCalledCount); // to page 1
- demo.find(`.${BASE_CLASS_PREFIX}-page .${BASE_CLASS_PREFIX}-page-item`)
- .at(1)
- .simulate('click', {
- nativeEvent: null,
- });
- expect(onChange.callCount).toBe(++onChangeCalledCount); // sort
- demo.find(`.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-sorter`).simulate('click', {
- nativeEvent: null,
- });
- expect(onChange.callCount).toBe(++onChangeCalledCount);
- });
- it(`test filter, and update dataSource with exist filter`, () => {
- const columns = [
- {
- className: 'name-col',
- title: 'Name',
- dataIndex: 'name',
- width: 150,
- filters: [
- {
- text: '名字包含"1"',
- value: '1',
- },
- {
- text: '名字包含"2"',
- value: '2',
- },
- ],
- onFilter: (value, record) => record.name.indexOf(value) > -1,
- },
- {
- title: 'Age',
- dataIndex: 'age',
- width: 150,
- sorter: (a, b) => (a.age - b.age > 0 ? 1 : -1),
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- ];
- const demo = mount(<Table dataSource={data} columns={columns} pagination={false}/>);
- demo.find(`.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-filter`).simulate('click'); // click first filter
- demo.find(`.${BASE_CLASS_PREFIX}-dropdown .${BASE_CLASS_PREFIX}-dropdown-item`)
- .at(0)
- .find(`.${BASE_CLASS_PREFIX}-checkbox`)
- .simulate('mousedown', {
- nativeEvent: null,
- });
- const nameColList = demo.find('.semi-table-tbody .name-col');
- const filteredData = data.filter(item => item.name.indexOf('1') > -1);
- expect(nameColList.length).toBe(filteredData.length); // update dataSource with exist filter
- const newData = getData(10);
- const newFilteredData = newData.filter(item => item.name.indexOf('1') > -1);
- demo.setProps({
- dataSource: newData,
- });
- demo.update();
- const newNameColList = demo.find('.semi-table-tbody .name-col');
- expect(newNameColList.length).toBe(newFilteredData.length);
- });
- it(`test controlled dataSource and columns`, async () => {
- let pagination = {
- currentPage: 1,
- total: data.length,
- pageSize: 10,
- };
- const getPageData = () =>
- data.slice(
- (pagination.currentPage - 1) * pagination.pageSize,
- pagination.currentPage * pagination.pageSize
- );
- let currentData = getPageData();
- let columns = [
- {
- title: 'Name',
- dataIndex: 'name',
- width: 150,
- filters: [
- {
- text: '名字包含"1"',
- value: '1',
- },
- {
- text: '名字包含"2"',
- value: '2',
- },
- ],
- onFilter: (value, record) => record.name.indexOf(value) > -1,
- },
- {
- title: 'Age',
- dataIndex: 'age',
- width: 150,
- sorter: true,
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- {
- render: (text, record) => (
- <Tooltip content={record.description}>
- <Tag color="green">Show Info</Tag>
- </Tooltip>
- ),
- width: 150,
- },
- ];
- const onChange = sinon.spy(({pagination: tablePagination, filters: tableFilters, sorters: tableSorters}) => {
- if (tablePagination && tablePagination.currentPage !== pagination.currentPage) {
- pagination.currentPage = tablePagination.currentPage;
- currentData = getPageData();
- columns = [...columns];
- demo.setProps({
- dataSource: currentData,
- columns,
- pagination,
- });
- }
- });
- const demo = mount(
- <Table onChange={onChange} dataSource={currentData} pagination={pagination} columns={columns}/>
- );
- const table = demo.find(BaseTable);
- demo.find(`.${BASE_CLASS_PREFIX}-page .${BASE_CLASS_PREFIX}-page-item`)
- .at(2)
- .simulate('click', {
- nativeEvent: null,
- });
- expect(onChange.called).toBe(true);
- expect(
- demo
- .find(`.${BASE_CLASS_PREFIX}-page .${BASE_CLASS_PREFIX}-page-item`)
- .at(2)
- .hasClass(`${BASE_CLASS_PREFIX}-page-item-active`)
- ).toBe(true);
- });
- it(`test resizable table`, async () => {
- let columns = [
- {
- title: 'Name',
- dataIndex: 'name',
- width: 150,
- filters: [
- {
- text: '名字包含"1"',
- value: '1',
- },
- {
- text: '名字包含"2"',
- value: '2',
- },
- ],
- onFilter: (value, record) => record.name.indexOf(value) > -1,
- },
- {
- title: 'Age',
- dataIndex: 'age',
- width: 150,
- sorter: true,
- },
- {
- title: 'Address',
- dataIndex: 'address',
- width: 300,
- },
- {
- render: (text, record) => (
- <Tooltip content={record.description}>
- <Tag color="green">Show Info</Tag>
- </Tooltip>
- ),
- },
- ];
- const expandedRowRender = (record, index, expanded) => (
- <article
- style={{
- margin: 0,
- }}
- >
- <p>{record.description}</p>
- </article>
- );
- const demo = mount(
- <Table columns={columns} dataSource={data} resizable expandedRowRender={expandedRowRender}/>
- );
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-thead .react-resizable-handle`).length).toBe(
- columns.reduce((count, col) => (typeof col.width === 'number' ? count + 1 : count), 0)
- );
- });
- it('test table sortOrder descend', async () => {
- const sortColumns = [
- {
- title: 'Name',
- dataIndex: 'name',
- sorter: (a, b) => a.name.length - b.name.length,
- sortOrder: 'descend',
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- ];
- const sortData = [
- {
- key: '1',
- name: 'John Brown',
- age: 32,
- address: 'New York No. 1 Lake Park',
- },
- {
- key: '2',
- name: 'Jim Green',
- age: 42,
- address: 'London No. 1 Lake Park',
- },
- {
- key: '3',
- name: 'Joe Black',
- age: 32,
- address: 'Sidney No. 1 Lake Park',
- },
- {
- key: '4',
- name: 'Jim Red',
- age: 32,
- address: 'London No. 2 Lake Park',
- },
- ];
- const targetData = sortData.reduce((a, b) => (a.name.length > b.name.length ? a : b));
- const {name} = targetData;
- const sortTable = mount(<Table columns={sortColumns} dataSource={sortData}/>);
- const firstCell = sortTable.find('.semi-table-tbody .semi-table-row .semi-table-row-cell').at(0); // console.log(sortTable.debug({ ignoreProps: true }));
- expect(firstCell.text()).toBe(name);
- });
- it('test table sortOrder ascend', async () => {
- const sortColumns = [
- {
- title: 'Name',
- dataIndex: 'name',
- sorter: (a, b) => a.name.length - b.name.length,
- sortOrder: 'ascend',
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- ];
- const sortData = [
- {
- key: '1',
- name: 'John Brown',
- age: 32,
- address: 'New York No. 1 Lake Park',
- },
- {
- key: '2',
- name: 'Jim Green',
- age: 42,
- address: 'London No. 1 Lake Park',
- },
- {
- key: '3',
- name: 'Joe Black',
- age: 32,
- address: 'Sidney No. 1 Lake Park',
- },
- {
- key: '4',
- name: 'Jim Red',
- age: 32,
- address: 'London No. 2 Lake Park',
- },
- ];
- const targetData = sortData.reduce((a, b) => (a.name.length < b.name.length ? a : b));
- const {name} = targetData;
- const sortTable = mount(<Table columns={sortColumns} dataSource={sortData}/>);
- const firstCell = sortTable.find('.semi-table-tbody .semi-table-row .semi-table-row-cell').at(0);
- expect(firstCell.text()).toBe(name);
- });
- it('test controlled sortOrder', async () => {
- const sortColumns = [
- {
- title: 'Name',
- dataIndex: 'name',
- sorter: (a, b) => a.name.length - b.name.length,
- sortOrder: 'descend',
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- ];
- const sortData = [
- {
- key: '1',
- name: 'long name',
- age: 32,
- address: 'New York No. 1 Lake Park',
- },
- {
- key: '2',
- name: 'longest name',
- age: 42,
- address: 'London No. 1 Lake Park',
- },
- {
- key: '3',
- name: 'longer name',
- age: 32,
- address: 'Sidney No. 1 Lake Park',
- },
- {
- key: '4',
- name: 'short',
- age: 32,
- address: 'London No. 2 Lake Park',
- },
- ];
- const targetData = sortData.reduce((a, b) => (a.name.length > b.name.length ? a : b));
- const {name} = targetData;
- const sortTable = mount(<Table columns={sortColumns} dataSource={sortData}/>);
- const firstCell = sortTable.find('.semi-table-tbody .semi-table-row .semi-table-row-cell').at(0);
- expect(firstCell.text()).toBe(name);
- const ascendOrderColumns = [
- {
- title: 'Name',
- dataIndex: 'name',
- sorter: (a, b) => a.name.length - b.name.length,
- sortOrder: 'ascend',
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- ]; // test sortOrder: ascend
- sortTable.setProps({
- columns: ascendOrderColumns,
- });
- sortTable.update();
- const ascendTargetData = sortData.reduce((a, b) => (a.name.length < b.name.length ? a : b));
- const {name: ascendTargetName} = ascendTargetData;
- const ascendFirstCell = sortTable.find('.semi-table-tbody .semi-table-row .semi-table-row-cell').at(0);
- expect(ascendFirstCell.text()).toBe(ascendTargetName); // test sortOrder: false, expect order as given data
- const defaultOrderColumns = [
- {
- title: 'Name',
- dataIndex: 'name',
- sorter: (a, b) => a.name.length - b.name.length,
- sortOrder: false,
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- ];
- sortTable.setProps({
- columns: defaultOrderColumns,
- });
- sortTable.update();
- const defaultTargetData = sortData[0];
- const {name: defaultTargetName} = defaultTargetData;
- const defaultFirstCell = sortTable.find('.semi-table-tbody .semi-table-row .semi-table-row-cell').at(0);
- expect(defaultFirstCell.text()).toBe(defaultTargetName);
- });
- it('test table select all when disabled all rows', async () => {
- const columns = [
- {
- title: 'Name',
- dataIndex: 'name',
- width: 150,
- },
- {
- title: 'Age',
- dataIndex: 'age',
- width: 150,
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- ];
- const rowSelection = {
- onSelectAll: sinon.spy(() => {
- }),
- getCheckboxProps: sinon.spy(record => ({
- disabled: true,
- // disabled all
- name: record.name,
- })),
- };
- const demo = mount(<Table columns={columns} dataSource={data} rowSelection={rowSelection}/>);
- demo.find(
- `.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-selection .${BASE_CLASS_PREFIX}-checkbox`
- ).simulate('click'); // should select 0 rows
- expect(rowSelection.onSelectAll.getCall(0).args[1].length).toBe(0);
- });
- it('test jsx async data', async () => {
- const asyncData = [
- {
- key: '1',
- name: 'John Brown',
- age: 32,
- address: 'New York No. 1 Lake Park, New York No. 1 Lake Park',
- },
- {
- key: '2',
- name: 'Jim Green',
- age: 42,
- address: 'London No. 1 Lake Park',
- },
- {
- key: '3',
- name: 'Joe Black',
- age: 32,
- address: 'Sidney No. 1 Lake Park',
- },
- {
- key: '4',
- name: 'Michael James',
- age: 99,
- address: 'Sidney No. 1 Lake Park',
- },
- ];
- const demo = mount(
- <Table dataSource={[]}>
- <Column title="Name" dataIndex="name" key="name" render={(text, record, index) => <a>{text}</a>}/>
- <Column title="Age" dataIndex="age" key="age"/>
- <Column title="Address" dataIndex="address" key="address"/>
- </Table>
- );
- setTimeout(() => {
- demo.setProps({
- dataSource: asyncData,
- });
- }, 2000);
- await sleep(3000);
- const baseTable = demo.find(BaseTable);
- expect(baseTable.state('cachedColumns').length).toEqual(3);
- expect(baseTable.state('dataSource').length).toEqual(4);
- });
- it('test cell align', async () => {
- const columns = getColumns();
- const alignRightColumns = columns.map(column => {
- column.align = 'right';
- return column;
- });
- const demo = mount(<Table dataSource={data} columns={alignRightColumns}/>);
- const titleAlignCells = demo.find(`.${BASE_CLASS_PREFIX}-table-align-right`);
- expect(titleAlignCells.length).toBeGreaterThan(0);
- const bodyAlignCells = document.querySelectorAll(`.${BASE_CLASS_PREFIX}-table-row-cell`);
- bodyAlignCells.forEach(cell => {
- expect(cell.style.textAlign).toEqual('right');
- });
- });
- it('test column className', async () => {
- const columns = getColumns();
- const alignRightColumns = columns.map(column => {
- column.className = 'test';
- return column;
- });
- const demo = mount(<Table dataSource={data} columns={alignRightColumns}/>);
- const titleAlignCells = demo.find(`.${BASE_CLASS_PREFIX}-table-row-head`);
- const bodyAlignCells = demo.find(`.${BASE_CLASS_PREFIX}-table-row-cell`);
- titleAlignCells.forEach(cell => {
- expect(cell.hasClass('test')).toBeTruthy();
- });
- bodyAlignCells.forEach(cell => {
- expect(cell.hasClass('test')).toBeTruthy();
- });
- });
- it('test header appearance', async () => {
- // object column
- const columns = getColumns();
- const demo = mount(
- <Table
- dataSource={data}
- columns={columns}
- scroll={{
- y: 500,
- }}
- />
- );
- expect(demo.find('.semi-table-thead').length).toEqual(1);
- demo.setProps({
- showHeader: false,
- });
- expect(demo.find('.semi-table-thead').length).toEqual(0); // jsx column
- const jsxColumns = getJSXColumns();
- const demo1 = mount(<Table dataSource={data}>{jsxColumns}</Table>);
- expect(demo1.find('.semi-table-thead').length).toEqual(1);
- demo1.setProps({
- showHeader: false,
- });
- expect(demo1.find('.semi-table-thead').length).toEqual(0);
- });
- it('test ref getCurrentPageData', async () => {
- // object column
- const pageSize = 10;
- const refObj = {
- current: null,
- };
- const columns = getColumns();
- const demo = mount(
- <Table
- dataSource={data}
- ref={refObj}
- columns={columns}
- pagination={{
- pageSize,
- }}
- />
- );
- const {dataSource} = refObj.current.getCurrentPageData();
- expect(dataSource.length).toEqual(pageSize); // jsx column
- const jsxColumns = getJSXColumns();
- const jsxRefObj = {
- current: null,
- };
- const jsxDemo = mount(
- <Table
- dataSource={data}
- ref={jsxRefObj}
- pagination={{
- pageSize,
- }}
- >
- {jsxColumns}
- </Table>
- );
- const {dataSource: jsxData} = jsxRefObj.current.getCurrentPageData();
- expect(jsxData.length).toEqual(pageSize);
- });
- it('test render expandIcon', async () => {
- const expandedRowRender = () => <div>Semi Design</div>;
- const columns = getColumns();
- const demo = mount(
- <Table
- dataSource={data}
- columns={columns}
- expandedRowRender={expandedRowRender}
- expandIcon={<IconStar size="small"/>}
- />
- );
- expect(demo.find('.semi-icon-star').length).toBeGreaterThan(0);
- const demo2 = mount(
- <Table
- dataSource={data}
- columns={columns}
- expandedRowRender={expandedRowRender}
- defaultExpandAllRows
- expandIcon={expanded => <div>{expanded && <IconStar size="small"/>}</div>}
- />
- );
- expect(demo2.find('.semi-icon-star').length).toBeGreaterThan(0);
- });
- it(`test onRow/onCell`, async () => {
- const onRowClick = sinon.spy(() => {
- });
- const onHeaderRowClick = sinon.spy(() => {
- });
- const onCellClick = sinon.spy(() => {
- });
- const onHeaderCellClick = sinon.spy(() => {
- });
- const onRow = sinon.spy((record, index) => ({
- className: 'test-row',
- onClick: onRowClick,
- }));
- const onHeaderRow = sinon.spy((record, index) => ({
- className: 'test-row',
- onClick: onHeaderRowClick,
- }));
- const columns = getColumns();
- const onCellColumns = columns.map((column, index) => {
- const style =
- index === 0
- ? {
- width: 200,
- height: 60,
- }
- : {};
- column.onCell = () => ({
- onClick: onCellClick,
- onCellClick,
- style,
- });
- column.onHeaderCell = () => ({
- onClick: onHeaderCellClick,
- style,
- });
- return column;
- });
- const demo = mount(<Table dataSource={data} onRow={onRow} onHeaderRow={onHeaderRow} columns={onCellColumns}/>);
- const tableCells = demo.find('.semi-table-body .semi-table-row-cell');
- const tableHeaderCells = demo.find('.semi-table-thead .semi-table-row-head'); // cell style
- expect(tableCells.at(0).instance().style.width).toEqual('200px');
- expect(tableCells.at(0).instance().style.height).toEqual('60px');
- expect(tableHeaderCells.at(0).instance().style.width).toEqual('200px');
- expect(tableHeaderCells.at(0).instance().style.height).toEqual('60px'); // body click
- tableCells.at(0).simulate('click');
- expect(onCellClick.called).toBeTruthy();
- const tableRows = demo.find('.semi-table-body .semi-table-row');
- tableRows.at(0).simulate('click');
- expect(onRowClick.called).toBeTruthy(); // header click
- tableHeaderCells.at(0).simulate('click');
- expect(onHeaderCellClick.called).toBeTruthy();
- const tableHeaderRows = demo.find('.semi-table-thead .semi-table-row');
- tableHeaderRows.at(0).simulate('click');
- expect(onHeaderRowClick.called).toBeTruthy();
- });
- it('test header merge', async () => {
- // 测试头部合并
- function testHeaderMerge(demo, params) {
- const rows = demo.find('.semi-table-thead .semi-table-row');
- expect(rows.length).toEqual(2);
- const firstRow = rows.at(0);
- const secondRow = rows.at(1);
- expect(firstRow.childAt(0).instance().colSpan).toEqual(2);
- expect(firstRow.childAt(1).instance().colSpan).toEqual(2);
- expect(firstRow.childAt(2).instance().colSpan).toEqual(1);
- expect(firstRow.childAt(2).instance().rowSpan).toEqual(2);
- expect(secondRow.childAt(0).instance().colSpan).toEqual(1);
- expect(secondRow.childAt(1).instance().colSpan).toEqual(1);
- expect(secondRow.childAt(2).instance().colSpan).toEqual(1);
- expect(secondRow.childAt(3).instance().colSpan).toEqual(1);
- }
- const nestData = getNestData();
- const filters = [
- {
- text: 'Code 45',
- value: '45',
- },
- {
- text: 'King 4',
- value: 'King 4',
- },
- ];
- const jsxDemo = mount(
- <Table dataSource={nestData}>
- <Column title={'Base Information'} dataIndex={'base'} fixed="left">
- <Column
- title={'Name'}
- dataIndex={'name'}
- fixed="left"
- width={200}
- filters={filters}
- onFilter={(value, record) => record.name.includes(value)}
- />
- <Column
- title={'Age'}
- dataIndex={'age'}
- width={100}
- fixed="left"
- sorter={(a, b) => (a.age - b.age > 0 ? 1 : -1)}
- />
- </Column>
- <Column title={'Company Information'} dataIndex={'company'}>
- <Column title={'Company Name'} dataIndex={'company.name'}/>
- <Column title={'Company Address'} dataIndex={'company.address'}/>
- </Column>
- <Column title={'Address'} dataIndex={'address'} width={250} fixed="right"/>
- </Table>
- );
- const columns = getNestColumns();
- const demo = mount(<Table dataSource={nestData} columns={columns}/>);
- testHeaderMerge(jsxDemo);
- testHeaderMerge(demo);
- });
- it('test without columns', async () => {
- const jsxDemo = mount(<Table dataSource={data}></Table>);
- const demo = mount(<Table dataSource={data} columns={[]}/>);
- expect(jsxDemo.find('.semi-table-row-head').length).toBe(0);
- expect(jsxDemo.find('.semi-table-row-cell').length).toBe(0);
- expect(demo.find('.semi-table-row-head').length).toBe(0);
- expect(demo.find('.semi-table-row-cell').length).toBe(0);
- });
- it('test useFullRender', async () => {
- const columns = [
- {
- dataIndex: 'name',
- width: 250,
- filters: [
- {
- text: '名字包含"1"',
- value: '1',
- },
- {
- text: '名字包含"2"',
- value: '2',
- },
- ],
- onFilter: (value, record) => record.name.indexOf(value) > -1,
- sorter: (a, b) => a.name.length - b.name.length,
- // 此处将useFullRender设置为true开启完全自定义渲染
- useFullRender: true,
- // 此处从render的第四个形参中解构出 展开按钮、选择按钮、文本等内容
- render: (text, record, index, {expandIcon, selection, indentText}) => {
- return (
- <span
- className="custom-render"
- style={{
- display: 'inline-flex',
- alignItems: 'center',
- justifyContent: 'center',
- }}
- >
- {indentText}
- {expandIcon}
- {selection}
- <span
- style={{
- marginLeft: 8,
- }}
- >
- {text}
- </span>
- </span>
- );
- },
- title: ({sorter, filter, selection}) => (
- <span
- className="custom-title"
- style={{
- display: 'inline-flex',
- alignItems: 'center',
- paddingLeft: 20,
- }}
- >
- {selection}
- <span
- style={{
- marginLeft: 8,
- }}
- >
- Name
- </span>
- {sorter}
- {filter}
- </span>
- ),
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- ];
- const rowSelection = {
- hidden: true,
- fixed: 'left',
- };
- const demo = mount(
- <Table
- rowSelection={rowSelection}
- columns={columns}
- dataSource={data}
- expandedRowRender={record => <article>{record.description}</article>}
- />
- );
- const node = demo.find('.custom-render').at(0);
- expect(node.children().length).toEqual(3);
- expect(node.childAt(0).exists('.semi-table-expand-icon')).toBeTruthy();
- expect(node.childAt(1).exists('.semi-table-selection-wrap')).toBeTruthy();
- const title = demo.find('.custom-title').at(0);
- expect(title.children().length).toEqual(4);
- expect(title.childAt(0).exists('.semi-table-selection-wrap')).toBeTruthy();
- expect(title.childAt(1).text()).toEqual('Name');
- expect(title.childAt(2).exists('.semi-table-column-sorter')).toBeTruthy();
- expect(title.childAt(3).exists('.semi-table-column-filter')).toBeTruthy();
- });
- it('test defaultExpandedRowKeys changed', async () => {
- const expandedRowRender = (record, index) => <div>{`Semi Design ${index}`}</div>;
- const pageSize = 20;
- const defaultExpandedRowKeys = Array.from({
- length: getRandomNumber(pageSize),
- }).map((_, i) => String(i));
- const newDefaultExpandedRowKeys = Array.from({
- length: getRandomNumber(pageSize),
- }).map((_, i) => String(i));
- const columns = getColumns();
- const demo = mount(
- <Table
- dataSource={data}
- columns={columns}
- expandedRowRender={expandedRowRender}
- defaultExpandedRowKeys={defaultExpandedRowKeys}
- pagination={{
- pageSize,
- }}
- />
- );
- expect(demo.find(BaseTable).state('expandedRowKeys').length).toEqual(defaultExpandedRowKeys.length);
- demo.setProps({
- defaultExpandedRowKeys: newDefaultExpandedRowKeys,
- });
- // 2.x defaultExpandedRowKeys 不再响应变化
- expect(demo.find(BaseTable).state('expandedRowKeys').length).toEqual(defaultExpandedRowKeys.length);
- });
- it('test getCheckboxProps changed', async () => {
- const defaultGetCheckboxProps = record => ({
- disabled: record.key === '1',
- });
- const newGetCheckboxProps = record => ({
- disabled: ['0', '1'].includes(record.key),
- });
- const columns = getColumns();
- const demo = mount(
- <Table
- dataSource={getData(20)}
- columns={columns}
- pagination={false}
- rowSelection={{
- getCheckboxProps: defaultGetCheckboxProps,
- }}
- />
- );
- expect(demo.find(BaseTable).state('disabledRowKeys').length).toEqual(1);
- demo.setProps({
- rowSelection: {
- getCheckboxProps: newGetCheckboxProps,
- },
- });
- expect(demo.find(BaseTable).state('disabledRowKeys').length).toEqual(2);
- });
- /**
- * 分页受控场景,更新数据后查看分页器是否保持当前页
- */
- it('test controlled pagination reset when dataSource change', async () => {
- const total = 100;
- const pagination = {
- pageSize: 10,
- currentPage: 2,
- };
- const columns = getColumns();
- const demo = mount(<Table dataSource={getData(total)} columns={columns} pagination={pagination}/>);
- const dataNum = getRandomNumber(100, 40);
- const newData = getData(dataNum);
- demo.setProps({
- dataSource: newData,
- });
- await sleep(2000);
- expect(
- demo
- .find(`.${BASE_CLASS_PREFIX}-page .${BASE_CLASS_PREFIX}-page-item-active`)
- .getDOMNode().innerHTML
- ).toBe('2');
- });
- /**
- * 分页非受控场景,更新数据后查看分页器是否重置
- */
- it('test uncontrolled pagination reset when dataSource change', async () => {
- const total = 100;
- const columns = getColumns();
- const demo = mount(<Table dataSource={getData(total)} columns={columns}/>);
- demo.find(`.${BASE_CLASS_PREFIX}-page .${BASE_CLASS_PREFIX}-page-item`)
- .at(2)
- .simulate('click');
- const dataNum = getRandomNumber(100, 40);
- const newData = getData(dataNum);
- demo.setProps({
- dataSource: newData,
- });
- await sleep(2000);
- demo.update();
- expect(demo.find(`.semi-page .semi-page-item-active`).getDOMNode().innerHTML).toBe('1');
- expect(demo.find(BaseTable).state('pagination')).toHaveProperty('currentPage', 1);
- });
- it('test pagination changed', async () => {
- const total = 100;
- const pagination = {
- pageSize: 10,
- currentPage: 2,
- };
- const newPagination = {
- pageSize: 5,
- currentPage: 1,
- };
- const columns = getColumns();
- const demo = mount(<Table dataSource={getData(total)} columns={columns} pagination={pagination}/>);
- const paginationProps = demo.find(BaseTable).state('pagination');
- expect(paginationProps.total).toEqual(total);
- expect(paginationProps.pageSize).toEqual(pagination.pageSize);
- expect(paginationProps.currentPage).toEqual(pagination.currentPage);
- demo.setProps({
- pagination: newPagination,
- });
- await sleep(2000);
- const newPaginationProps = demo.find(BaseTable).state('pagination');
- expect(newPaginationProps.pageSize).toEqual(newPagination.pageSize);
- expect(newPaginationProps.currentPage).toEqual(newPagination.currentPage);
- });
- it(`test grouped data change dataSource`, async () => {
- const data = getGroupData();
- const columns = getGroupColumns();
- const groupedRowClick = sinon.spy();
- const rowKey = record =>
- `${record.city && record.city.toLowerCase()}-${record.job && record.job.toLowerCase()}`;
- const demo = mount(
- <Table
- dataSource={data}
- rowKey={rowKey}
- groupBy={'city'}
- columns={columns}
- renderGroupSection={groupKey => <strong>Jobs in {groupKey}:</strong>}
- onGroupedRow={(group, index) => ({
- onClick: groupedRowClick,
- })}
- clickGroupedRowToExpand
- scroll={{
- y: 480,
- }}
- />
- );
- const newData = [
- {
- city: 'Tianjin',
- job: 'FE',
- department: 'IES',
- },
- {
- city: 'Tianjin',
- job: 'Android',
- department: 'IES',
- },
- {
- city: 'Wuhan',
- job: 'Android',
- department: 'IES',
- },
- {
- city: 'Wuhan',
- job: 'SE',
- department: 'EE',
- },
- {
- city: 'Chengdu',
- job: 'Android',
- department: 'EE',
- },
- {
- city: 'Chengdu',
- job: 'IOS',
- department: 'EE',
- },
- {
- city: 'Xiamen',
- job: 'SE',
- department: 'DATA',
- },
- {
- city: 'Xiamen',
- job: 'IOS',
- department: 'DATA',
- },
- ];
- demo.setProps({
- dataSource: newData,
- });
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-row-section`).length).toBe(4);
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-body .${BASE_CLASS_PREFIX}-table-row`).length).toBe(0);
- demo.find(`.${BASE_CLASS_PREFIX}-table-row-section`)
- .at(0)
- .simulate('click');
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-row`).length).toBeGreaterThan(0);
- });
- it(`test given object columns and children`, async () => {
- const demo = mount(
- <Table dataSource={data} columns={columns}>
- <Table.Column title="Age" dataIndex="age" key="age"/>
- </Table>
- );
- const test = demo.find(BaseTable); // 同时传columns与children时,columns优先
- expect(test.state('cachedColumns')).toEqual(columns);
- expect(test.state('queries').length).toEqual(columns.length);
- });
- it('test header colSpan', async () => {
- const columns = [
- {
- title: 'Name',
- dataIndex: 'name',
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Home phone',
- colSpan: 2,
- dataIndex: 'tel',
- },
- {
- title: 'Phone',
- colSpan: 0,
- dataIndex: 'phone',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- },
- ];
- const data = [
- {
- key: '1',
- name: 'ZhangSan',
- age: 50,
- tel: '010-20000000',
- phone: 10010,
- address: 'BeiJing No.1 High School',
- },
- {
- key: '2',
- name: 'LiSi',
- tel: '010-30000000',
- phone: 10086,
- age: 40,
- address: 'ShangHai No. 1 High School',
- },
- {
- key: '3',
- name: 'WangWu',
- age: 60,
- tel: '010-40000000',
- phone: 10011,
- address: 'NaiJing No.1 High School',
- },
- {
- key: '4',
- name: 'XiaoMing',
- age: 20,
- tel: '010-50000000',
- phone: 12580,
- address: 'ShiJiaZhuang No.1 High School',
- },
- {
- key: '5',
- name: 'XiaoHong',
- age: 40,
- tel: '010-60000000',
- phone: 12530,
- address: 'TaiBei No.2 High School',
- },
- ];
- const demo = mount(<Table dataSource={data} columns={columns}/>);
- expect(demo.find('.semi-table-row .semi-table-row-head').length).toBe(columns.length - 1);
- });
- it('test expandAllRows', async () => {
- const expandedRowRender = () => <div>Semi Design</div>
- const initData = [];
- const columns = getColumns();
- const demo = mount(<Table
- dataSource={initData}
- columns={columns}
- expandedRowRender={expandedRowRender}
- pagination={false}
- expandAllRows
- />);
- const newData = getData(20);
- demo.setProps({dataSource: newData});
- demo.update();
- const expandedRows = demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row-expanded`)
- expect(expandedRows.length).toEqual(newData.length);
- // 动态切换 expandAllRows
- demo.setProps({expandAllRows: false});
- demo.update();
- const newExpandedRows = demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row-expanded`)
- expect(newExpandedRows.length).toEqual(0);
- });
- it(`test defaultExpandAllGroupRows`, async () => {
- const data = getGroupData();
- const columns = getGroupColumns();
- const rowKey = record => `${record.city && record.city.toLowerCase()}-${record.job && record.job.toLowerCase()}`;
- const groupSize = new Set(data.map(item => item.city)).size;
- const demo = mount(
- <Table
- dataSource={data}
- rowKey={rowKey}
- groupBy={'city'}
- columns={columns}
- renderGroupSection={groupKey => <strong>Jobs in {groupKey}:</strong>}
- scroll={{y: 480}}
- defaultExpandAllGroupRows
- />
- );
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row-section.on`).length).toBe(groupSize);
- });
- it(`test expandAllGroupRows`, async () => {
- const data = getGroupData();
- const groupSize = new Set(data.map(item => item.city)).size;
- const columns = getGroupColumns();
- const rowKey = record => `${record.city && record.city.toLowerCase()}-${record.job && record.job.toLowerCase()}`;
- const demo = mount(
- <Table
- dataSource={[]}
- rowKey={rowKey}
- groupBy={'city'}
- columns={columns}
- renderGroupSection={groupKey => <strong>Jobs in {groupKey}:</strong>}
- scroll={{y: 480}}
- expandAllGroupRows={true}
- />
- );
- demo.setProps({dataSource: data});
- demo.update();
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row-section.on`).length).toBe(groupSize);
- demo.setProps({expandAllGroupRows: false});
- demo.update();
- expect(demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row-section.on`).length).toBe(0);
- });
- it('test defaultSortOrder descend', async () => {
- const sortColumns = [
- {
- title: 'Name',
- dataIndex: 'name',
- sorter: (a, b) => a.name.length - b.name.length,
- defaultSortOrder: 'descend',
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- }
- ];
- const sortData = [
- {
- key: '1',
- name: 'long name',
- age: 32,
- address: 'New York No. 1 Lake Park',
- },
- {
- key: '2',
- name: 'longest name',
- age: 42,
- address: 'London No. 1 Lake Park',
- },
- {
- key: '3',
- name: 'longer name',
- age: 32,
- address: 'Sidney No. 1 Lake Park',
- },
- {
- key: '4',
- name: 'short',
- age: 32,
- address: 'London No. 2 Lake Park',
- },
- ];
- const onChange = sinon.spy(() => {
- });
- // test default descend
- const targetData = sortData.reduce((a, b) => a.name.length > b.name.length ? a : b);
- const {name} = targetData;
- const sortTable = mount(<Table columns={sortColumns} dataSource={sortData} onChange={onChange}/>);
- const firstCell = sortTable.find('.semi-table-tbody .semi-table-row .semi-table-row-cell').at(0);
- expect(firstCell.text()).toBe(name);
- sortTable.unmount();
- });
- it('test defaultSortOrder descend', async () => {
- const ascendOrderColumns = [
- {
- title: 'Name',
- dataIndex: 'name',
- sorter: (a, b) => a.name.length - b.name.length,
- defaultSortOrder: 'ascend',
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- }
- ];
- const sortData = [
- {
- key: '1',
- name: 'long name',
- age: 32,
- address: 'New York No. 1 Lake Park',
- },
- {
- key: '2',
- name: 'longest name',
- age: 42,
- address: 'London No. 1 Lake Park',
- },
- {
- key: '3',
- name: 'longer name',
- age: 32,
- address: 'Sidney No. 1 Lake Park',
- },
- {
- key: '4',
- name: 'short',
- age: 32,
- address: 'London No. 2 Lake Park',
- },
- ];
- const onChange = sinon.spy(() => {
- });
- const sortTable = mount(<Table columns={ascendOrderColumns} dataSource={sortData} onChange={onChange}/>);
- const ascendTargetData = sortData.reduce((a, b) => a.name.length < b.name.length ? a : b);
- const {name: ascendTargetName} = ascendTargetData;
- const ascendFirstCell = sortTable.find('.semi-table-tbody .semi-table-row .semi-table-row-cell').at(0);
- expect(ascendFirstCell.text()).toBe(ascendTargetName);
- sortTable.unmount();
- });
- it('test defaultSortOrder false', async () => {
- const sortColumns = [
- {
- title: 'Name',
- dataIndex: 'name',
- sorter: (a, b) => a.name.length - b.name.length,
- defaultSortOrder: false,
- },
- {
- title: 'Age',
- dataIndex: 'age',
- },
- {
- title: 'Address',
- dataIndex: 'address',
- }
- ];
- const sortData = [
- {
- key: '1',
- name: 'long name',
- age: 32,
- address: 'New York No. 1 Lake Park',
- },
- {
- key: '2',
- name: 'longest name',
- age: 42,
- address: 'London No. 1 Lake Park',
- },
- {
- key: '3',
- name: 'longer name',
- age: 32,
- address: 'Sidney No. 1 Lake Park',
- },
- {
- key: '4',
- name: 'short',
- age: 32,
- address: 'London No. 2 Lake Park',
- },
- ];
- const onChange = sinon.spy(() => {
- });
- const sortTable = mount(<Table columns={sortColumns} dataSource={sortData} onChange={onChange}/>);
- // test default false
- const defaultTargetData = sortData[0]
- const {name: defaultTargetName} = defaultTargetData;
- const defaultFirstCell = sortTable.find('.semi-table-tbody .semi-table-row .semi-table-row-cell').at(0);
- expect(defaultFirstCell.text()).toBe(defaultTargetName);
- // test click sorter
- sortTable.find(`.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-sorter`).at(0).simulate('click', {nativeEvent: null});
- expect(onChange.callCount).toBe(1);
- expect(onChange.getCall(0).args[0].sorter.sortOrder).toBe('ascend');
- sortTable.find(`.${BASE_CLASS_PREFIX}-table-thead .${BASE_CLASS_PREFIX}-table-column-sorter`).at(0).simulate('click', {nativeEvent: null});
- expect(onChange.callCount).toBe(2);
- expect(onChange.getCall(1).args[0].sorter.sortOrder).toBe('descend');
- // test change data
- const newData = [
- {
- key: '1',
- name: 'longest name',
- age: 18,
- address: 'New York No. 1 Lake Park',
- },
- {
- key: '2',
- name: 'long name',
- age: 20,
- address: 'London No. 1 Lake Park',
- },
- {
- key: '3',
- name: 'longer name',
- age: 16,
- address: 'Sidney No. 1 Lake Park',
- },
- {
- key: '4',
- name: 'short',
- age: 33,
- address: 'London No. 2 Lake Park',
- },
- ];
- sortTable.setProps({dataSource: newData});
- sortTable.update()
- const newDescendTargetData = newData.reduce((a, b) => a.name.length > b.name.length ? a : b);
- const {name: newDescendTargetName} = newDescendTargetData;
- const newDataFirstCell = sortTable.find('.semi-table-tbody .semi-table-row .semi-table-row-cell').at(0);
- expect(newDataFirstCell.text()).toBe(newDescendTargetName);
- sortTable.unmount();
- });
- it(`test expandRowByClick`, async () => {
- const onExpand = sinon.spy();
- const onExpandedRowsChange = sinon.spy();
- const demo = mount(
- <Table
- columns={columns}
- dataSource={data}
- onExpand={onExpand}
- onExpandedRowsChange={onExpandedRowsChange}
- expandedRowRender={() => <div>Semi Design</div>}
- expandRowByClick
- />
- );
- const table = demo.find(BaseTable);
- const rows = demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row`);
- rows.at(0).simulate('click');
- rows.at(1).simulate('click');
- expect(onExpand.calledTwice).toBeTruthy();
- expect(onExpandedRowsChange.calledTwice).toBeTruthy();
- expect(onExpand.getCall(1).args[0]).toEqual(true);
- expect(onExpand.getCall(1).args[1]).toEqual(data[1]);
- expect(onExpand.getCall(1).args[2].constructor.name).toBe('SyntheticEvent');
- expect(onExpandedRowsChange.getCall(1).args[0].length).toEqual(2);
- expect(table.state(`expandedRowKeys`)).toEqual(['0', '1']);
- const expandedRows = demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row-expanded`);
- expandedRows.at(0).simulate('click');
- // 查看点击第二次是否折叠
- const newExpandedRows = demo.find(`.${BASE_CLASS_PREFIX}-table-tbody .${BASE_CLASS_PREFIX}-table-row-expanded`)
- expect(newExpandedRows.length).toEqual(1);
- expect(table.state(`expandedRowKeys`)).toEqual(['1']);
- });
- it(`test expanded row re-render`, () => {
- const expandedRowRender = sinon.spy(() => <div>Semi Design</div>);
- const demo = mount(
- <Table
- columns={columns}
- dataSource={data}
- expandedRowRender={expandedRowRender}
- />
- );
- const table = demo.find(BaseTable);
- const expandIcons = demo.find(`.semi-table-tbody .semi-table-row .semi-table-expand-icon`);
- expandIcons.at(0).simulate('click');
- expandIcons.at(1).simulate('click');
- expect(expandedRowRender.calledTwice).toBeTruthy();
- });
- it('test defaultFilteredValue is in onChange when click sorter', () => {
- const columns = [
- {
- title: '标题',
- dataIndex: 'name',
- width: 400,
- render: (text, record, index) => {
- return (
- <div>
- {text}
- </div>
- );
- },
- filters: [
- {
- text: 'Semi Design 设计稿',
- value: 'Semi Design 设计稿',
- },
- {
- text: 'Semi Pro 设计稿',
- value: 'Semi Pro 设计稿',
- },
- ],
- onFilter: (value, record) => record.name.includes(value),
- defaultFilteredValue: ['Semi Pro 设计稿'],
- },
- {
- title: '大小',
- dataIndex: 'size',
- sorter: (a, b) => a.size - b.size > 0 ? 1 : -1,
- defaultSortOrder: 'ascend',
- render: (text) => `${text} KB`
- },
- {
- title: '所有者',
- dataIndex: 'owner',
- render: (text, record, index) => {
- return (
- <div>
- {text}
- </div>
- );
- }
-
- }
- ];
- const getData = (total) => {
- const data = [];
- for (let i = 0; i < total; i++) {
- const isSemiDesign = i % 2 === 0;
- const randomNumber = (i * 1000) % 199;
- data.push({
- key: '' + i,
- name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi Pro 设计稿${i}.fig`,
- owner: isSemiDesign ? '姜鹏志' : '郝宣',
- size: randomNumber,
- avatarBg: isSemiDesign ? 'grey' : 'red'
- });
- }
- return data;
- };
- const data = getData(25);
- const onChange = sinon.spy(() => {
- });
- const tableNode = mount(<Table columns={columns} dataSource={data} onChange={onChange}/>);
- tableNode.find('.semi-table-column-sorter').simulate('click');
- expect(onChange.calledOnce).toBe(true);
- const arg = onChange.getCall(0).args[0];
- expect(arg.filters.length).toBe(1);
- expect(arg.filters[0].defaultFilteredValue).toEqual(['Semi Pro 设计稿']);
- expect(arg.filters[0].filteredValue).toEqual(['Semi Pro 设计稿']);
- tableNode.unmount();
- });
- it('test defaultSortOrder is in onChange when click filter', () => {
- const defaultSortOrder = 'ascend';
- const columns = [
- {
- title: '标题',
- dataIndex: 'name',
- width: 400,
- render: (text, record, index) => {
- return (
- <div>
- {text}
- </div>
- );
- },
- filters: [
- {
- text: 'Semi Design 设计稿',
- value: 'Semi Design 设计稿',
- },
- {
- text: 'Semi Pro 设计稿',
- value: 'Semi Pro 设计稿',
- },
- ],
- onFilter: (value, record) => record.name.includes(value),
- defaultFilteredValue: ['Semi Pro 设计稿'],
- },
- {
- title: '大小',
- dataIndex: 'size',
- sorter: (a, b) => a.size - b.size > 0 ? 1 : -1,
- defaultSortOrder: 'ascend',
- render: (text) => `${text} KB`
- },
- {
- title: '所有者',
- dataIndex: 'owner',
- render: (text, record, index) => {
- return (
- <div>
- {text}
- </div>
- );
- }
-
- }
- ];
- const getData = (total) => {
- const data = [];
- for (let i = 0; i < total; i++) {
- const isSemiDesign = i % 2 === 0;
- const randomNumber = (i * 1000) % 199;
- data.push({
- key: '' + i,
- name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi Pro 设计稿${i}.fig`,
- owner: isSemiDesign ? '姜鹏志' : '郝宣',
- size: randomNumber,
- avatarBg: isSemiDesign ? 'grey' : 'red'
- });
- }
- return data;
- };
- const data = getData(25);
- const onChange = sinon.spy(() => {
- });
- const tableNode = mount(<Table columns={columns} dataSource={data} onChange={onChange}/>);
- tableNode.find('.semi-table-column-filter').simulate('click');
- const filterNode = Array.from(document.querySelectorAll('.semi-checkbox-addon')).filter(node => node.textContent === 'Semi Design 设计稿');
- const mousedownEvent = new MouseEvent('mousedown', {
- bubbles: true,
- cancelable: true,
- button: 0,
- });
- filterNode[0].dispatchEvent(mousedownEvent);
- expect(onChange.calledOnce).toBe(true);
- const arg = onChange.getCall(0).args[0];
- expect(arg.sorter.defaultSortOrder).toBe(defaultSortOrder);
- expect(arg.sorter.sortOrder).toBe(defaultSortOrder);
- tableNode.unmount();
- });
- });
|