javascript - 模拟 Div 点击 Enzyme 和 React

标签 javascript reactjs testing redux enzyme

我正在学习 Enzyme,我已经开始对团队编写的应用程序编写一些测试。我正在尝试模拟点击一个元素。该应用程序基本上有一个列表,只要您单击它,就会出现一个复选标记(的图像)。如果您再次单击,则不会出现(的图像)复选标记。应用程序通过在您单击元素时更改状态来执行此操作,然后确定要呈现的图像。

它适用于实际应用程序,但不知何故 Enzyme 失败了。关于 enzyme ,我是否遗漏了什么?

下面是一些简化的代码。这是类(class):

class RecipeInfo extends Component {

  constructor(props) {
    super(props);
    this.state = {};
    this.doneClick = this.doneClick.bind(this);
  }

  doneClick(event) {
    let index = event.target.name;
    let state = {};
    state[index] = !this.state[index];
    this.setState(state)
  }

  renderIngredients(ingredients) {
   let quantities = ingredients.quantity;
   let lines = [];
   for(let i = 0; i < quantities.length; i++){
     lines.push(
      <div className='flex-body-ingredients' key={i}>
        <div onClick={this.doneClick} id={i} >
        {this.state[i] ? 
          (<img className='empty-check' src="/assets/success.png" alt="success" name={i} />)
          : (<img className='empty-check' src="/assets/oval.png" name={i} alt="oval" />)}
        </div>
      </div>
       )
     }
     return lines.map((line) => line)
   }

  render() {
    return (
      {this.renderIngredients(ingredients)}
    )
  }
}

function mapStateToProps(state) {
  return {
    recipe: state.recipes.selectedRecipe
  }
}
export default connect(mapStateToProps, actions)(RecipeInfo);

下面是我刚刚写的测试:

describe('Recipe Info', () => {
  const recipeInfo = mount(<Provider store={createRecipeStore}><RecipeInfo/></Provider>);

  it('shows a click and then hides the click when clicking an ingredient', () => {
    const notChecked = recipeInfo.find('[alt="oval"]').first();
    expect(notChecked).toBeDefined();

    recipeInfo.find('.flex-body-ingredients').first().childAt(0).simulate('click');

    const checked = recipeInfo.find('[alt="success"]').first();
    expect(checked).toBeDefined();
  });

});

当我运行测试并记录该元素的控制台时,我看到以下内容:

<div id="0"><img class="empty-check" src="/assets/oval.png" name="0" alt="oval"></div>

这在点击后永远不会改变。

最佳答案

我发现了问题。这是因为我没有将事件处理程序传递到模拟中。

我必须将其更改为:

recipeInfo.find('.flex-body-ingredients').first().childAt(0).simulate('click', {target: {name: 0}});

关于javascript - 模拟 Div 点击 Enzyme 和 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43566125/

相关文章:

javascript - 如何让 child 影响 React 中的 parent ?

c# - 在这种情况下,我应该对所有可能的输入进行单元测试吗?

javascript - 通过 javascript 与 Firefox 插件交互

javascript - 如何使程序在不重新输入的情况下恢复为原始文本

javascript - 如何在 html 页面上插入 m3u 播放列表?

testing - 在小 cucumber 中编写场景的最佳方式

java - 弹出新窗口时控件不会切换

javascript - 通过弹出窗口更改网址

javascript - ReactJS错误: "Uncaught TypeError: this.props.alarms.forEach is not a function"

reactjs - 基于 Typescript 的 React : importScripts() gives: 'importScripts' is not defined no-undef