从Jest将值传递给箭头函数

时间:2020-06-10 15:48:03

标签: javascript reactjs jestjs

我正在为我的应用程序编写Jest测试用例,并且具有箭头功能

Product.js

import React from 'react';

class Products extends React.Component {
     constructor() {
    super();
    this.state = {
        prodName: '',
        prodID: '',
        brandName: '',
        prodNameHidden: true,
        brandNameHidden: true,
        idHidden: true,
       }
    }
     handleChange = type => (event) => {
          console.log(type)
          if(type == 'add') {
            var key = event.target.name;
            var val = event.target.value;
            switch (key) {
             case "prodName": 
                this.setState({prodNameHidden: true})
             break;
             case "brandName":
                this.setState({brandNameHidden: true})
             break;
             case "prodID":
                this.setState({idHidden: true})
             break
        }
        this.setState({[key]: val});
     }
     else if(type == "edit") {
          //Statements for type:edit
    }
     render() {
       return (
       <div>
         <span hidden={this.state.prodNameHidden} className="inpSpan errSpan">Please enter the product name</span>
                <label className="inpLabel"><span className="inpSpan">* </span>Product Name:</label>
                <input className="inp" type="text" placeholder="Enter the product name" onChange={this.handleChange("add")} name="prodName" value={this.state.prodName}/>

                <span hidden={this.state.brandNameHidden} className="inpSpan errSpan">Please enter the brand name</span>
                <label className="inpLabel"><span className="inpSpan">* </span>Brand Name:</label>
                <input className="inp" type="text" placeholder="Enter the brand name" onChange={this.handleChange("add")} name="brandName" value={this.state.brandName}/>

                <span hidden={this.state.idHidden} className="inpSpan errSpan">Please enter the product ID</span>
                <label className="inpLabel"><span className="inpSpan">* </span>Product ID:</label>
                <input className="inp" type="number" placeholder="Enter the product ID" onChange={this.handleChange("add")} name="prodID" value={this.state.prodID}/>
       </div>
      );
}
export default Product;

在Jest中,我需要使用虚拟值测试handleChange()。

Product.test.js

//have initialized wrapper in beforeEach()
it("Should do something", () => {
    dummyEvent = {
        target: {
           value: "dummyValue",
           name: "dummyName"
        }
   }
   wrapper.setState({
        prodName: '',
        prodID: '',
        brandName: '',
        prodNameHidden: ,
        brandNameHidden: true,
        idHidden: true,
    })
    wrapper.instance().handleChange("add", dummyEvent);
    expect(wrapper.state().prodName).toBe("dummyValue");
})

但是我无法对其进行测试,因为JEST无法找到该功能

测试结果

预期:dummyValue

收到:“'

我们将不胜感激。

0 个答案:

没有答案