| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175 |
- 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('click', {
- 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('click', {
- 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('click', {
- 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 设计稿');
- filterNode[0].click();
- 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();
- });
- });
|