【问题标题】:Jest/Enzyme | ComponentDidMount doesn't get called when it should笑话/酶 | ComponentDidMount 在它应该被调用的时候没有被调用
【发布时间】:2019-03-13 23:43:50
【问题描述】:

我有一个执行fetchUser() 的componentDidMount。我正在尝试测试componentDidMount

组件代码:

static propTypes = {
    match: PropTypes.shape({
      isExact: PropTypes.bool,
      params: PropTypes.object,
      path: PropTypes.string,
      url: PropTypes.string
    }),
    label: PropTypes.string,
    actualValue: PropTypes.string,
    callBack: PropTypes.func
  };

  state = {
    user: {}
  };

  componentDidMount() {
    this.fetchUser();
  }

  getUserUsername = () => {
    const { match } = this.props;
    const { params } = match;
    return params.username;
  };

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

测试:

    it('should call fetchUsers function only once', () => {
      const match = { params: { username: 'testUser' }, isExact: true, path: '', url: '' };
      const fetchUserFn = jest.fn(match);
      const wrapper = shallow(<UserDetailsScreen match={match} fetchUsers={fetchUserFn} />);
      wrapper.instance().componentDidMount(match);
      expect(fetchUserFn).toHaveBeenCalledTimes(1); // I get expected 1 and got 0
    });

我的意思是为什么这个componentDidMount() 的测试与我的其他测试不同?在过去的几周里,我已经测试了其中很多,从来没有这个问题。也许是因为getUser() 是一个承诺,我需要模拟它。以前有没有人偶然发现过这样的事情?

getUser()的代码

export const getUser = username => {
  const options = {
    method: httpMethod.GET,
    url: endpoint.GET_USER(username)
  };
  return instance(options);
};

【问题讨论】:

  • 我将发布整个组件,但是如果我使用 wrapper.debug() 打印,我可以看到整个组件正在渲染,并且在我检查填充的特定数据的其他测试中,那些测试通过。

标签: javascript reactjs unit-testing jestjs enzyme


【解决方案1】:

我开玩笑地使用spyOn() 找到了解决方案。不知道为什么,我需要监视这个特定的用例,但如果可以请解释一下。解决方法如下:

    it('should call fetchUsers function only once', () => {
      const match = { params: { username: 'testUser' }, isExact: true, path: '', url: '' };
      const fetchUserFn = jest.fn(match);
      const spy = jest.spyOn(UserDetailsScreen.prototype, 'componentDidMount');
      const wrapper = shallow(<UserDetailsScreen match={match} fetchUsers={fetchUserFn} />, {
        disableLifecycleMethods: true
      });
      wrapper.instance().componentDidMount(match);
      expect(spy).toHaveBeenCalledTimes(1);
    });

这里有一个警告。如果您不使用disableLifecycleMethods,该函数将被调用两次。如果我没记错的话,每次渲染一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多