首页 > 解决方案 > 笑话/酶 | 无法在 null 或 undefined 上解构属性

问题描述

我正在尝试测试我的功能ComponentDidMount。但我得到这个错误:Cannot destructure property params on null or undefined

我要测试的功能是这个:

  componentDidMount() {
    this.fetchUser();
  }

这取决于这个:

  fetchUser = () => {
    getUser(this.getUserUsername()).then(username => {
      this.setState({
        user: username.data
      });
    });
  };

作为回报,这取决于这个:

  getUserUsername = () => {
    const { match } = this.props;
    const { params } = match;
    console.log(params, 'params'); // return an object { username: "john" }
    console.log(match, 'match');
    **// return an object
    // { isExact: true
    //  params:
    // username: "john" .
    // __proto__: Object
    // path: "/management/users/:username"
    // url: "/management/users/john" }**
    return params.username;
  };

这是我的测试:

  describe('componentDidMount', () => {
    it('should call fetchUsers function', () => {
      const match = { params: 'testName' };
      const params = match;
      const fetchUserFn = jest.fn(params);
      const wrapper = shallow(<UserDetailsScreen fetchUsers={fetchUserFn} />, {
        disableLifecycleMethods: true
      });
      wrapper.instance().componentDidMount();
      expect(fetchUserFn).toHaveBeenCalledTimes(1);
    });
  });

但我收到上述错误。不知道我需要做什么,虽然我找到了与这个问题类似的答案,但答案并没有解决我的问题。

获取用户的代码:


export const getUser = username => {
  const options = {
    method: httpMethod.GET,
    url: endpoint.GET_USER(username)
    // The GET_USER is an endpoint for 
    // that specific username
  };
  return instance(options);
};

以上返回一个承诺。

标签: javascriptreactjsunit-testingjestjsenzyme

解决方案


试试下面的语法

describe('componentDidMount', () => {
  it('should call fetchUsers function', () => {
    const match={params: {username: 'akshay'}, isExact: true, path: "", url: ""}
    const fetchUserFn = jest.fn(match);
    const wrapper = shallow(<UserDetailsScreen match={match} fetchUsers={fetchUserFn} />, {
      disableLifecycleMethods: true
    });
    expect(wrapper.containsMatchingElement(<h2>Details for 1</h2>)).toBeTruthy();
  });
});

你也可以使用containsMatchingElement


推荐阅读