React.js-用酶模拟点击 [英] React.js - Simulating a click with Enzyme

查看:65
本文介绍了React.js-用酶模拟点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个React.js应用程序,它是一个简单的购物车应用程序. https://codesandbox.io/s/znvk4p70xl

I have this React.js app that is a simple Cart app. https://codesandbox.io/s/znvk4p70xl

问题是我正在尝试使用Jest和Enzyme对应用程序的状态进行单元测试,但它似乎无法正常工作.这是我的 Todo.test.js 单元测试:

The problem is I am trying to unit test the state of the application using Jest and Enzyme but it does not seem to work. Here is my Todo.test.js unit test:

import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Todo from '../components/Todo';

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

test('Test it', async () => {
  // Render a checkbox with label in the document
  const cart = [
    { name: 'Green', cost: 4 },
    { name: 'Red', cost: 8 },
    { name: 'Blue', cost: 14 }
  ];

  const wrapper = mount(<Todo cart={cart} />);
  const firstInput = wrapper.find('.name');
  firstInput.simulate('change', { target: { value: 'Pink' } });

  const firstCost = wrapper.find('.cost');
  firstCost.simulate('change', { target: { value: 200 } });

  const submitButton = wrapper.find('.addtocart');
  submitButton.simulate('click');

  wrapper.update();

  expect(wrapper.state('price')).toBe(26);

  console.log(wrapper.state());
  console.log(wrapper.props().cart);

});

当我运行测试时,当应该添加项目 Pink 时,购物车仍会说同样的话.

When I run the test, the cart still says the same thing when the item Pink should have been added.

当我模拟 addToCart 方法上的按钮单击时,怎么可能?

How can this be when I have simulated a button click on the addToCart method?

 PASS  src/__tests__/todo.test.js
  ● Console
    console.log src/__tests__/todo.test.js:32      { price: 26 }    
console.log src/__tests__/todo.test.js:33      [ { name: 'Green', cost: 4 },        { name: 'Red', cost: 8 },        { name: 'Blue', cost: 14 } ]

推荐答案

您试图模拟对类 addtocart 的元素的点击.但是,您没有元素为 addtocart 类.您的添加按钮的元素ID为 submit .

You are attempting to simulate a click on an element with class addtocart. However, you don't have an element with class addtocart. Your add button has an element ID of submit.

更改此:

const SubmitButton = wrapper.find('.addtocart');

对此:

const SubmitButton = wrapper.find('#submit');

这篇关于React.js-用酶模拟点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆