简体   繁体   English

在 React JS 中,如何对容器中的 function 进行单元测试?

[英]In React JS, how to do unit testing on a function which is in a container?

I am trying to simulate on click of a button and test what's happening based on that click.我正在尝试模拟单击按钮并测试基于该单击发生的情况。 I tried mocking function.我试过 mocking function。 But didn't work.但是没有用。 How do we test the statements inside of a function?我们如何测试 function 内部的语句?

I tried mocking a function to see if it has been called.我试过 mocking 一个 function 看看它是否被调用。 But i always get mock function not called但我总是得到模拟 function not called

updateSelect =(e, model) => {
    window.alert('test');
    const value = e.type === "keyup" ? 
    e.target.parentNode.childNodes[2].innerText : e.target.innerText;
    if(!isEmpty(value)){
      this.setState({text: value});
      this.props.returnedValue({name : model, value});
    }
}

<button className="test" onClick={(e)=>this.updateSelect(e, model)}>Click</button>

I expect either the function should be called or at least few statements in the function has to be executed我希望应该调用 function 或者至少必须执行 function 中的几个语句

You cannot mock function which is inside the component.您不能模拟组件内部的 function。 You have to get element by className or element and simulate click event.您必须通过类名或元素获取元素并模拟点击事件。 While simulating click event make sure that you are passing that 2 params(Mock 2 params and pass it).在模拟点击事件时,请确保您传递了 2 个参数(模拟 2 个参数并传递它)。 Hope you are using Enzyme and Jest/Mocha.希望您使用的是 Enzyme 和 Jest/Mocha。 For your reference Link .供您参考链接

Also in assertions check the expected output of the function(Value in state, etc) and don't check whether the function is called or not.同样在断言中检查函数的预期 output(state 中的值等),不要检查是否调用了 function。

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

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