javascript - Jest 与 enzyme |在 componentDidMount 中测试 PropTypes 函数

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

我收到一条错误,指出 spy On 只能应用于函数。有人可以帮我测试一下吗。 componentDidMountonCreateUserSucess。我什至尝试模拟这些功能,但总是失败。

最佳答案

测试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();
      });
   });
});

关于javascript - Jest 与 enzyme |在 componentDidMount 中测试 PropTypes 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54907756/

相关文章:

javascript - 如何在Shiny中用JavaScript改变UI元素的属性?

javascript - 如何编写 javascript 漂亮的时间函数

reactjs - Jest/React/Redux 错误 : Actions may not have an undefined "type" property. 您是否拼错了常量?行动: {}

reactjs - 导入图像会破坏 Jest 测试

javascript - 脚本不按 ID 定位某些元素,但在其他元素上运行良好

javascript - 通过 Bacon.js 使用多个事件流值

reactjs - Firebase - firestore createdAt 时间戳 - react

javascript - 如何在 react 表上实现延迟加载数据?

javascript - ReactJS:未知类型的参数不可分配给来自文件读取器的 SetStateAction<string> 类型的参数

jestjs - 如何解决 Jest Mock 错误 "Cannot find module"