【问题标题】:Enzyme is not testing onChange methodEnzyme 没有测试 onChange 方法
【发布时间】:2019-04-01 04:11:31
【问题描述】:

我正在尝试通过将模拟数据传递给 App.test.js 的 on change 方法来进行测试,但是我收到以下错误。

● 应该处理 onChange 事件 › 应该处理 onChange 事件

expect(received).toEqual(expected)

Expected value to equal:
  "Owl"
Received:
  undefined

Difference:

  Comparing two different types of values. Expected string but received undefined.

我查看了一个类似的帖子

onChange - Testing using Jest Enzyme - check?,但是他们的答案没有帮助

App.js

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import Card from './Card';
import PropTypes from "prop-types";
const Styles = {
    marginTop: '100px',
    inputStyle: {
        borderRadius: '0px',
        border: 'none',
        borderBottom: '2px solid #000',
        outline: 'none',
        focus: 'none'
    }
}
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            query: '',
            title: undefined,
            url: undefined
        }
        this.onChange = this.onChange.bind(this);
    }
    onChange(e) {
        this.setState({query: e.target.value})
    }
    getGIY = async(e) => {
        e.preventDefault();
        const { query } = this.state;
        await fetch(`http://api.giphy.com/v1/gifs/search?q=${query}&api_key=iBXhsCDYcnktw8n3WSJvIUQCXRqVv8AP&limit=5`)
        .then(response => response.json())
        .then(({ data }) => {
          this.setState({
            title: data[0].title,
            url: data[0].images.downsized.url
          });
        })
        .catch(console.log);
    }
    render() {
        return (
            <div className="col-md-6 mx-auto" style={Styles}>
                <h1 className="gif-title">Random GIF fetch</h1>
                <form className="form-group" onSubmit={this.getGIY}>
                    <input
                        style={Styles.inputStyle}
                        className="form-control"
                        type="text"
                        name="query"
                        onChange={this.onChange}
                        placeholder="Search GIF..."/>
                    <button type="submit" className="btn btn-primary mt-4">Get GIF</button>
                </form>
                <Card title={this.state.title} url={this.state.url}/>
            </div>
        );
    }
}
PropTypes.propTypes = {
    onChange: PropTypes.func.isRequired,
    getGIY:PropTypes.func.isRequired,
    title:PropTypes.string.isRequired,
    url:PropTypes.string.isRequired
}
export default App;

App.test.js

import React from 'react';
import ReactDOM from 'react-dom';
import {shallow} from 'enzyme';
import App from './App';


describe('Should render App Component', ()=> {
  it('should render app component', ()=> {
    const component = shallow(<App />);
  })
})

describe('Should have h1 title', ()=> {
  it('Should show Random GIF fetch', ()=>{
    const component = shallow(<App/>);

    expect(component.find("h1.gif-title")).toHaveLength(1);
    expect(component.find("h1.gif-title").text()).toContain("Random GIF fetch")
  })
})



describe('Should handle onChange event', ()=> {
  it('should handle onChange event', ()=> {
    const component = shallow(<App/>)
    const form = component.find('input')

    form.props().onChange({
      target:{
        title: 'Owl',
        query: 'Owl',
        url: 'https://media.giphy.com/media/qISaMW1xwmvNS/giphy.gif'
      }
    });
    expect(component.state('query')).toEqual('Owl')

  })
})

【问题讨论】:

    标签: javascript jestjs enzyme


    【解决方案1】:

    您的事件处理程序根据e.target.value 设置状态:

    onChange(e) {
        this.setState({query: e.target.value})
    }
    

    ...但是您在模拟事件中没有为 target.value 传递任何内容。

    把你的测试改成这样:

    describe('Should handle onChange event', ()=> {
      it('should handle onChange event', ()=> {
        const component = shallow(<App/>)
        const form = component.find('input')
    
        form.props().onChange({
          target:{
            value: 'Owl'
          }
        });
        expect(component.state('query')).toEqual('Owl')  // Success!
      })
    })
    

    ...它应该可以工作。

    【讨论】:

    • 它成功了,谢谢。什么是测试 onSubmit 处理程序的最佳方法是它处理 api fetch ?什么是一个很好的资源/文档/指南来查看
    • 您需要在 global 对象上模拟 fetch。我实际上没有看到任何 SO 答案显示如何为 React 组件函数执行此操作。如果您想创建一个新问题,我将发布一个答案,指导您完成操作。 @randal
    • 好的,我想弄清楚,如果我被卡住了......我会发布一个问题,只是希望答案很快就会出现:) 再次感谢。
    • 是的,我被卡住了 :'(, stackoverflow.com/questions/55462069/…
    猜你喜欢
    • 2021-02-22
    • 2020-11-28
    • 2018-07-25
    • 1970-01-01
    • 2019-08-02
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多