【问题标题】:React Redux Test failed because it can't fetch data throught actionReact Redux 测试失败,因为它无法通过操作获取数据
【发布时间】:2018-11-06 17:57:50
【问题描述】:

我正在尝试使用 Jest 和 Enzyme 测试我的智能组件,但它没有要呈现的数据,因为它应该是通过操作获取的。错误是:getTasks is not a function

Enzyme.configure({ adapter: new Adapter() });

describe('Main', () => {
  describe('when loading is true', () => {
    it('should render loading div', () => {
      const wrapper = mount(<Main.WrappedComponent loading={true} />);
      expect(wrapper.html()).toEqual('<div>Loading</div>');
      wrapper.unmount();
    });
  });
});

这是我正在尝试测试的组件,它通过操作获取数据,然后用它们做一些事情,但如果没有数据(loading === true)它只会渲染带有“正在加载”文本的&lt;div&gt; . getTasks() 只是import 数据:

class Main extends React.Component {
  constructor(props) {
    super();
    this.handleData = this.handleData.bind(this);
    this.handleHigh = this.handleHigh.bind(this);
  }

  componentDidMount() {
    const { getTasks } = this.props;
    getTasks();
  }

  render() {
    const { data, loading } = this.props;
    if (!loading) {
      this.handleData(data);
      return (
          {data.map(task => {
            if (task.obj_status === 'active') 
              return (
               // Doing some stuff with data here
              );
    } else {
      return <div>Loading</div>;
    }
  }
}

const mapStateToProps = state => ({
  data: state.main.data,
  loading: state.main.loading
});

const mapDispatchToProps = dispatch => ({
  ...bindActionCreators(
    {
      getTasks: loadTasks,
      dispatch
    },
    dispatch
  )
});

export default withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps
  )(Main)
);

【问题讨论】:

  • 你能展示 WrappedComponent 吗?
  • 您需要模拟来自服务器的响应。您可以使用 nock 模块
  • @AdrianPażucha 完成
  • @IuriiBudnikov 它只是从本地存储导入,没有服务器甚至fetch func,但我明白你的意思。你可以给我一个例子的链接吗?
  • @IuriiBudnikov 我检查了nock,但它仅适用于 HTTP 请求,我那里没有 HTTP

标签: javascript reactjs react-redux jestjs enzyme


【解决方案1】:

你需要将 getTasks 作为一个函数传入你的 props:

const wrapper = mount(<Main.WrappedComponent loading={true} getTasks={() => {}} />);

当 Enzyme 挂载时,它会调用 componentDidMount 并调用未定义的 prop 并炸毁

【讨论】:

  • 非常感谢!这对我有用。但是如果我想测试这个组件的正确渲染,我想用getTasks()做什么?
  • 我建议你使用 Sinon 来存根这个函数,你可以确保它在你期望的时候被调用。我将进行另一个测试,将data 提供到您的组件中,然后您可以断言map 函数正确输出元素
  • 所以只在我的测试中描述虚拟data
  • 是的,使用您期望的正确格式。您可以提供一些 obj_status of 'active',以测试那里的 if 语句,以及一个不同的 obj_status 并确保该元素不会被渲染
  • 好的,知道了!再次感谢您!
【解决方案2】:

更好的解决方案是模拟函数:

const getTasksMock = jest.fn();
const wrapper = mount(<Main.WrappedComponent loading={true} getTasks={getTasksMock}/>);

然后你可以检查调用函数,例如:toHaveBeenCalled() https://jestjs.io/docs/en/expect.html#tohavebeencalled

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 2021-04-04
    • 2023-04-03
    相关资源
    最近更新 更多