开玩笑和酶失灵的模拟功能

时间:2019-10-04 12:50:54

标签: reactjs jestjs enzyme

试图通过模拟功能与基本的React应用程序一起使用来进行简单测试,但是失败了,我无法查明哪里出了问题。有人可以让我挺直吗?

Main App.js

    import React, { Component } from 'react';
    import './App.css';
    import List from './List';

    class App extends Component {

      state = {
        count: 0,
        newItem: '',
        items: ['apple', 'milk'] 
      }

      addItem = () => {
        if (this.state.newItem) {
       this.setState({ count: this.state.count + 1, items: [...this.state.items, this.state.newItem], newItem: '' })
       } 
      }

      render() {

      return(
      <div className="App">

         <header className="App-header">
          <h1>30 days of React</h1>
          <h2>Day Thirty / Testing React Components</h2>
          <p>Total Items: {this.state.count}</p>
         </header>

         <div className="container">
          <input type='text' value={this.state.newItem} onChange={e => this.setState({ newItem: e.target.value})}></input>
          <button className='main-btn' onClick = {this.addItem}>Add To List</button>
         </div>

        <div>
          <List items={this.state.items}/>
        </div>

        </div>

        ) 
       }
     }

    export default App;

测试

//define empty mock function to simulate the click 
const mockClick = jest.fn();

describe('App component mock test', () => {
    it('button click should fire function', () => {
        const component = shallow(<App onClick={mockClick} />);

        const input = component.find('input');
        input.simulate('change', {target: {value: 'test'} });

        const button = component.find('button.main-btn');
        button.simulate('click');
        expect(mockClick).toHaveBeenCalled();
    });
}); 

还有一个功能组件可以显示列表,但是由于这是一个浅浅的测试,因此不应起作用。

1 个答案:

答案 0 :(得分:0)

确定了。天啊基本上,我只是对模拟如何工作及其用例感到困惑。我明白了用onCick作为道具创建了一个子组件,以简单地测试该函数是否正在触发,现在可以正常工作了。

测试

const mockClick = jest.fn();

describe('ListItem component mock tests', () => {
    it('button click should fire function', () => {
        const component = shallow(<ListItem onClick={mockClick} />);

        const button = component.find('button.smallbtn');
        button.simulate('click');
        expect(mockClick).toHaveBeenCalled();
    });
});

我正在测试的子组件

import React from 'react';
const ListItem = ( props ) => {

return (

  <div>
    <p>{props.item}</p>
    <button className="smallbtn" onClick={() => props.onClick(props.id)}>delete</button>  
  </div>

  );
};

export default ListItem;