【问题标题】:How to test conditional rendering of components using Jest and Enzyme如何使用 Jest 和 Enzyme 测试组件的条件渲染
【发布时间】:2019-04-20 23:00:54
【问题描述】:

我的 React 组件中有一个条件渲染块,定义为:

 {(props.email.primary.isPending) ?
          <PendingComponent emailAddress={props.email.primary.pendingEmail} />
          :
          <SecondaryEmailContact
            state={props.email.secondary}
            retrieveInputData={props.retrieveInputData}
            handleSecondaryEmailToggle={props.handleSecondaryEmailToggle}
            handleDelete={props.handleDelete}
            handleSubmitContact={props.handleSubmitContact}
            refs={props.refs}
          />
        }

我写了一个测试用例如下:

it('renders the EditEmailContact component', () => {
        wrapper=mount(<EditEmailContact 
          email={emailState}
          handleSecondaryEmailToggle={handleSecondaryEmailToggleFn}
          retrieveInputData={retrieveInputDataFn}
          handleDelete={handleDeleteFn}
          handleSubmitContact={handleSubmitContactFn} />);
    });
  });

因此,在我的测试结果中,它显示了定义条件渲染语句的行未测试。那么,如何测试条件渲染呢?

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:

    您可以创建两个不同的测试用例,将道具传递给您的组件。例如:

    const yourProps = {
        email: {
          primary: {
             isPending: true // create test cases passing a different value
          },
    
        },
      }
    
      const component = mount(<YourComponent {...yourProps} />)
    

    【讨论】:

    • @pranami 很高兴它帮到了你!编码愉快!
    • @pranami 顺便说一下,你也可以考虑为这个测试用例添加一个快照,例如expect(component).toMatchSnapshot()
    • 我已经添加了一个快照。实际上我正在测试的组件有很多子组件,大约 10-15 个猜测。所以我有一个疑问是:现在我已经导入了所有子组件到我的测试文件并尝试调用浅/安装内的组件来调用它,这样我看到每个文件的覆盖率都在增加。但我只是想确认这是否是正确的方法。你能告诉我这样做是否正确吗?
    • 另外,我的组件内部有一些功能,就像点击按钮可以改变状态并打开一个对话框,那么我该如何测试这些功能呢?
    • @pranami 请创建一个新问题并将其链接到此处,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2017-04-13
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2020-05-10
    • 2017-02-12
    相关资源
    最近更新 更多