如何测试是否在带有笑话/酶的组件中调用了导入类的方法?

时间:2019-06-27 18:58:56

标签: javascript reactjs jestjs enzyme

我在组件中有这样的代码:

export class VehiclesComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    };
    autoBind(this);
  }

  componentDidMount () {
    this.fetchData();
  }

  fetchData() {
    const {
      query,
      filter,
      hasAccess,
      value2,
      value,
      value3,
      name,
      topics,
    } = this.props;
    const { data } = this.state;

    if (value || value2) {
      return DataService.getCars(
        filter,
        hasAccess,
        name,
        topics,
      ).then((cars) => {
        this.setState({
          data: [...data, ...cars],
        });
      });
    } else if (value3) {
      return DataService.getBuses(
        filter,
        hasAccess,
        query,
      ).then((buses) => {
        this.setState({
          data: [...data, ...buses],
        });
      });
    }
  };

  render() {
    return(...)
  }
};

我的问题是我不知道如何根据传递的props(值,value2或value3)正确测试调用了哪个服务。我想测试是否调用了DataService.getBuses或DataService.getCars。我试图模拟该服务:

import DataService from '../../services/DataService';
jest.mock("../../services/DataService");


DataService.mockImplementation(() => {
    return {
      getCars: () => Promise.resolve([])
    }
  });

但是我的测试仍然失败,我有 TypeError:无法读取未定义的属性“ then”

  35 |
  36 |   componentDidMount() {
> 37 |     DataService.getCars().then(cars => {});

1 个答案:

答案 0 :(得分:0)

我通过以下操作解决了这个问题:

void OnTick()
{    ...
     for ( a = 1; a < L / 2; a++ )
     {     ...
           if ( s <= S ) break;
           ...
     }
     Comment( "  S= ", S,
              ", A= ", A,
              ", B= ", B
              );
     return;
}