如何通过酶单元测试的正确道具?

How to pass correct props for enzyme unit test?

我有一个组件主要是returns html.

//MainRender.js
function changeOnClick(arg){
  return (
    console.log(arg)
  )
};
    
function helper1(arg) {
  return (
    <div className="helper1" onClick={(e) => changeOnClick(e.target.value)}>
      <span> Helper1: {arg.isHelper1} </span>
    </div>
  );
}

function helper2(arg) {
  return (
    <div className="helper2" >
      <span> Helper2: {arg.isHelper2} </span>
    </div>
)};

export default function MainRender(props){
  const theValue = props.value;
  if(theValue.isHelper1){
    return helper1(theValue)
  } else {
    return helper2(theValue)
  }
 };

我的测试是,

import { mount } from 'enzyme';
import React from 'react';

import MainRender from './MainRender';

describe("Testing MainRender", () => {
  it("it should return true when isHelper1 is true", ()=> {
    const tempValue = {"value": {"isHelper1":true, "isHelper2": false}};
    const wrapper = mount(<MainRender props={tempValue} />); // error occurs here
 }
});
Error: Uncaught [TypeError: Cannot read property 'isHelper1' of undefined]

当我调试这个测试时,它的结构实际上是这样的,

props
  |-props
      |-value
         |-isHelper1
         |-isHelper2

我认为问题是,props 是嵌套的,没有正确分配给 theValue。如何在酶单元测试中正确传递参数?该函数本身工作正常。

您向不需要的组件添加了额外的 props 属性。 JSX 的属性将组成 props 对象。应该是:

const tempValue = { value: { isHelper1: true, isHelper2: false } };
const wrapper = mount(<MainRender {...tempValue} />);