reactjs - 使用 Jest 和 Enzyme 测试 React 组件 : where to test whether component props were given

标签 reactjs testing components jestjs enzyme

在使用 Jest & Enzyme 为 React 组件编写测试时,哪些测试应该负责确保为组件提供某些 props?

<App>
  <Somewhere>
    <MyNestedComp someProps={someValue} />
  </Somewhere>
</App>

在上面的例子中,我们应该在哪里测试以确保 MyNestedComp 被赋予了 someProps Prop 。目前,我测试了我的每个组件,有时对在哪里测试这些细节感到有点困惑。

最佳答案

您应该首先开始测试您传递 prop 的组件本身,无论传递的 prop 在组件本身是否可用,是否正确呈现相应的 html。

您可以使用 enzyme 的浅层渲染将自己限制在您正在测试的特定组件上。

例如

假设在 MyNestedComp 中,我使用传递的 prop someProps 显示在一些 html 元素中。

const MyNestedComp = ({someProps}) => {
return (
        <div> 
           <h1>{someProps}</h1>
        </div>
  )
}

MyNestedComp 的单元测试可以写成 -

const wrapper = shallow(<MyNestedComp someProps={"someValue"} />);
expect(wrapper.html()).to.equal('<div><h1>someValue</h1></div>');

然后您可以为父组件编写测试用例,也可以在示例中的 Somewhere 编写测试用例。 您可以检查从父组件传递的 prop 是否正确到达子组件,并且可以进行许多其他测试用例。

  <Somewhere>
    <MyNestedComp someProps={someValue} />
  </Somewhere>

Somewhere 的单元测试用例可以写成 -

const wrapper = shallow(       
      <Somewhere>
        <MyNestedComp someProps={someValue} />
      </Somewhere>
);

const childWrapper = wrapper.find('MyNestedComp');
expect(childWrapper).to.have.length(1);
expect(wrapper.find({someProps: 'someValue'})).to.have.length(1);

expect(wrapper.prop('someProps')).to.equal("someValue");

希望对你有帮助。

关于reactjs - 使用 Jest 和 Enzyme 测试 React 组件 : where to test whether component props were given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42169522/

相关文章:

javascript - 如何解决TypeError : arr[Symbol. iterator] is not a function in my React project

css - 仅当组件适合 flex 容器时才渲染它们

ruby-on-rails - Rails 5 测试不会重现 PATCH 上的实际行为

java - 我如何使用 spring Autowiring 使用内存中的 derby 数据库来使用一堆 DAO?

angular - 如何将输入标签的ngModel值获取到angularjs4中的组件中?

reactjs - 是否可以将 react-datepicker 与 react 钩子(Hook)形式一起使用?

reactjs - 从 firebase 进行 react 读取,出现错误

python - 任何好的 Python HTTP 代理?

javascript - 引用错误 : Cannot access 'UserContext' before initialization - React

delphi - Delphi 中要避免的组件