笑话和酵素|在componentDidMount中测试PropTypes函数

时间:2019-02-27 14:30:53

标签: javascript reactjs jestjs enzyme

我的组件中有此代码,该代码将listUsers作为必需的PropType函数。我想测试一下componentDidMount()中它应该只被调用一次。

组件代码:

   static propTypes = {
    securityMode: PropTypes.string.isRequired,
    listUsers: PropTypes.func.isRequired
  };

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

    onCreateUserSucess= response => {
    this.setState({ isCreateUserModalOpen: false });
    const { listUsers, notify } = this.props;
    listUsers();
    this.closeCreateUserModal();
    notify({
      title: 'Created User',
      message: `User ${response.username} was added to group: ${response.group}`,
      status: STATUS.success,
      dismissible: true,
      dismissAfter: 3000
    });
  };

我得到一个错误,说spyOn仅适用于函数。有人可以帮我测试一下。 componentDidMountonCreateUserSucess。我什至尝试模拟函数,但总是失败。

1 个答案:

答案 0 :(得分:2)

测试componentDidMount非常简单。假设您在上面创建的组件称为UsersDisplayer

class UsersDisplayer extends Component {
   constructor(props) {
      // ...
   }

   // The code above goes here.
}

为了测试listUsers函数是否运行,您应该执行以下操作:

// Import React, shallow and UsersDisplayer at the top.

describe('<UsersDisplayer />', () => {
   let usersDisplayerWrapper;
   let listUsers;

   beforeEach(() => {
      listUsers = jest.fn();

      usersDisplayerWrapper = <UsersDisplayer listUsers={listUsers} />;
   });

   describe('componentDidMount', () => {
      it('calls listUsers props function', () => {
          // The `componentDidMount` lifecycle method is called during the rendering of the component within the `beforeEach` block, that runs before each test suites.
         expect(listUsers).toHaveBeenCalled();
      });
   });

   describe('onCreateUserSucess', () => {
      it('calls listUsers props function', () => {
         // Create a dummy `response` data that will be passed to the function.
         const response = {
            username: 'username',
            group: 'group'
         };

         // Simply just call the function of the instance.
         usersDisplayerWrapper.instance().onCreateUserSucess(response);

         expect(listUsers).toHaveBeenCalled();
      });
   });
});