简体   繁体   English

如何使用 jest 和 react 测试库为返回 function 的嵌套 jsx 编写测试用例

[英]how to write test case for nested jsx returning function using jest and react testing library

export default function App() {
  let arr = [{name:"a"},{name:"b"},{name:"c"},{name:"d"},{name:"e"},{name:"f"}]

  let **renderFn** = () => {
    return arr.map(a=>{
      return <div>{a.name}</div>
    })
  }
  return (
    <div className="App">
      <div>{renderFn()}</div>
    </div>
  );
}

How to test test nested function that returns a complete jsx and that function is invoked in the jsx itself.如何测试测试嵌套的 function,它返回一个完整的 jsx 并且 function 在 jsx 本身中被调用。 I am unable to write test我无法编写测试

Do not use a nested function, instead move your function outside of the function App.不要使用嵌套的 function,而是将您的 function 移到 function App 之外。 Declare it as a "First-class citizen", as a function that you export.将其声明为“一等公民”,即您导出的 function。

Dependency injection what ever your function needs should be passed as arguments.依赖注入无论你的 function 需要什么,都应该作为 arguments 传递。

Now you can test your function as a stand alone unit.现在您可以将 function 作为独立单元进行测试。

export function List({ list }) {
    return list.map(a => {
        return <div>{a.name}</div>
    })
}  
export default function App() {
    let arr = [{ name: "a" }, { name: "b" }, { name: "c" }, { name: "d" }, { name: "e" }, { name: "f" }]
    return (
        <div className="App">
            <div><List list={arr} /></div>
        </div>
    );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 React 测试库为返回 Jest 中的组件的 Switch 语句编写单元测试用例 - How to write Unit Test case for Switch Statement that returns Component in Jest with React Testing Library 如何使用 React、Jest 和 React-testing-library 为带有令牌的 api 调用编写单元测试? - How can I write unit test for api call with token using React, Jest and React-testing-library? 如何使用 onClick 函数 Jest/React 测试库测试 React 组件 - How to test react component with onClick function Jest/React testing library 使用 JEST 和 React 测试库在 Onclick Function 中测试 API 调用 - Test API call in Onclick Function using JEST and React Testing Library 如何使用Jest和Enzyme为简单的React组件编写测试用例 - How to write a test case for a simple React component using Jest and Enzyme 如何使用 React 测试库和 jest 测试条件渲染的字符串 - How to test conditionally rendered string using React testing library and jest 如何使用 Jest 和 React 测试库测试 className - How to test a className with the Jest and React testing library 在点击处理程序中测试 function - Jest,React 测试库 - Test the function inside click handler - Jest, React testing Library 使用 react-testing-library 和 jest 测试是否调用了 prop 函数 - Testing if a prop function was called using react-testing-library and jest 如何使用 Jest 测试库 React Native - How to test a library React Native using Jest
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM