mercredi 25 décembre 2019

About testing HOC component

I have a component wrapped by withStyles and withTranslation HOC, now I wanna do a shallow testing the component but I don't know how to get the wrapped component. Just a simple test: all fields should be rendered, so I don't wanna use mount for this, and I can't make export default because it had a default one. This is my code:

import React, { Component } from 'react';
import { withStyles, Grid, TextField, Button } from '@material-ui/core';
import { createShallow } from '@material-ui/core/test-utils';
import { withTranslation } from 'react-i18next';
import { styles } from '.MyStyles';

export const MyComponent = withTranslation(withStyles(styles)(class extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isWrong: false,
      isEmpty: false,
      value: '',
    }
    onChange = (e) => {
      const { value } = this.state;
      e.preventDefault();
      this.setState({value: e.targer.value});
      value==''?this.setState({isEmpty: true}):this.setState({isEmpty: false});
    }
    onClick = () => {
      const { isEmpty } = this.state;
      isEmpty?this.setState({isWrong: true}):this.setState({isWrong: false});
    }
  }
  render() {
    const { classes, t } = this.props;
    const { isWrong, value } = this.state;
    return (
      <div>
        <Grid container className={classes.content1}>
          <Grid item>{t('Task 1')}</Grid>
          <Grid item>{t('Task 2')}</Grid>
        </Grid>
        <Grid container className={classes.content2}>
          <div>{t('Task 3')}</div>
          <TextField label={t('Info')} value={value} error={isWrong} onChange={this.onChange}></TextField>
          <Button variant="contained" onClick={this.onClick}>{t('Change')}</Button>
        </Grid>
      </div>
    );
  }
}));

{...}

and this is my test:

describe("check", () => {
  let shallow;
  let wrapper;
  beforeEach(() => {
    shallow = createShallow();
    wrapper = shallow(<MyComponent />);
  });
  it("check component render right", () => {
    const div = wrapper.find('div');
    expect(div).toMatchSnapshot();
    expect(div).toHaveLength(1);
  });
});

Aucun commentaire:

Enregistrer un commentaire