选项卡的材料UI + Jest +酶测试

时间:2020-03-15 15:28:17

标签: reactjs jestjs material-ui enzyme

我正在尝试测试具有选项卡的组件。我的第一个测试将确保初始状态正确,而随后的测试将确保在单击另一个选项卡后将更改状态。我在material-uijest中使用enzyme

import React, { useState } from 'react';

import { Grid, Typography, Tabs, Tab, CircularProgress, Button } from '@material-ui/core';
import useStyles from './styles';

const TabExample = () => {
  const classes = useStyles();
  const [activeTab, setActiveTab] = useState(0);

  return (
    <Grid container className={classes.container}>
      <div className={classes.formContainer}>
        <div className={classes.form}>
          <Tabs
            id="tabs"
            value={activeTab}
            onChange={(_e, id) => setActiveTab(id)}
            indicatorColor="primary"
            textColor="primary"
            centered
          >
            <Tab label="Tab1" classes={{ root: classes.tab }} />
            <Tab label="Tab2" classes={{ root: classes.tab }} />
          </Tabs>
          {activeTab === 0 ? (
            <div>TAB 1 </div>
          ) : (
            <div>TAB 1 </div>
          )}
        </div>
      </div>
    </Grid>
  ) 
}

我尝试了一些解决方案,但都无法使用,并且不确定该文档的存放位置。这是我尝试过的:

import TabExample from '../TabExample';

it('Tab is changed when tab is clicked', () => {
  const wrapper = mount(
    <Provider>
       <TabExample />
    </Provider>,
  );

  // prints tabs component
  console.log(wrapper.find('#tabs').debug());

  // prints nothing
  console.log(wrapper.find('WithStyles(Grid)').debug());

  // prints first tab
  console.log(wrapper.find('#tabs button').first().debug());

  // TypeError: Cannot read property 'value' of undefined
  console.log(wrapper.find('#tabs button').value.debug());
});

不确定如何获取

1 个答案:

答案 0 :(得分:0)

我知道了:

it('Initial tab is 0', () => {
    expect(
      wrapper
        .find('WithStyles(ForwardRef(Tabs))')
        .childAt(0)
        .props().value,
    ).toBe(0);

    expect(
      wrapper
        .find('WithStyles(ForwardRef(Tab))')
        .at(0)
        .props().selected,
    ).toBe(true);

  });