笑话/酶|无法对null或未定义的属性进行解构

时间:2019-03-12 09:31:35

标签: javascript reactjs unit-testing jestjs enzyme

我正在尝试测试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);
    });
  });

但是我得到了上面的错误。不确定我需要做什么,虽然我找到了与此问题相似的答案,但这些答案并不能解决我的问题。

getUser的代码:


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);
};

以上内容返回了承诺。

2 个答案:

答案 0 :(得分:1)

尝试以下语法

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

答案 1 :(得分:0)

您出于某种原因正在破坏parmas,您是说params吗?

尝试在整个APP中搜索parmas,并检查是否存在拼写错误。