简体   繁体   English

Mocking a function 在被测组件内 Reactjs

[英]Mocking a function inside a component under test Reactjs

Can we mock a function which is written inside the component under test in Reactjs?我们可以模拟一个 function,它写在 Reactjs 的被测组件内吗?

You cannot directly mock a function but there are ways you could get it working.您不能直接模拟 function 但有一些方法可以让它工作。 You could pass the function in props and call that instead of using the original function.您可以在 props 中传递 function 并调用它,而不是使用原始的 function。

For example例如

const MyComponent = () => {
   const myFunction = () => {
      // Your code here
   };
   // rest of the code
}

You can turn this into你可以把它变成

const MyComponent = ({myMockedFunction}) => {
   const myFunction = myMockedFunction || (() => {
      // Your code here
   });
   // rest of the code
}

Other ways include refactoring the function outside so you can use jest.mock directly.其他方法包括在外部重构 function 以便您可以直接使用 jest.mock。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM