如何在ReactJS组件单元测试中“模拟”状态值?

时间:2017-09-20 07:21:05

标签: reactjs unit-testing redux

我正在尝试对我的ReactJS组件进行单元测试。基本上它是一个由输入和按钮组成的简单组件。当点击按钮时,它会触发一个名为'onSave'的事件,只有当state.textValue不为空时才调用'this.props.addTodo':

import React, {Component, PropTypes} from 'react';

export default class Invoer extends Component {

    static propTypes = {
        saveTodo: PropTypes.func.isRequired
    }

    constructor(props) {
        super();
        this.props = props;
        this.state = {textValue: ''};
    }


    onChange = (event) => {
        if (event.target.value !== '') {
            this.setState({textValue: event.target.value});
            console.log(event.target.value);
        }
    }

    onSave = () => {
        if (this.state.textValue!== '') {
            this.props.saveTodo(this.state.textValue);
        }
    }

    render() {
        return (
            <header>
                <input type="text" value={this.state.textValue} onChange={this.onChange}/>
                <button onClick={this.onSave}>save</button>
            </header>
        );
    }
}

我为onSave事件编写了一个单元测试。唯一的问题是我无法弄清楚如何“模拟”this.state.textValue以便在第26行设置状态见上文:

import React from 'react';
import Invoer from "../components/Invoer";
import {createRenderer} from 'react-test-renderer/shallow';
it('should call this.props.saveTodo event when clicking on button on non empty value', () => {
    const props = {
        saveTodo: jest.fn()
    }

    const renderer = createRenderer();
    renderer.render(<Invoer {...props} />)
    const output = renderer.getRenderOutput()

    //tried to mock the state.textValue, results in error:
    //output.props.children[0].value = 'hoera';

    output.props.children[1].props.onClick();

    expect(props.saveTodo).toBeCalled()
});

运行此测试时出现此错误:

should call this.props.saveTodo event when clicking on button on non empty value
    expect(jest.fn()).toBeCalled()    
    Expected mock function to have been called.

当然是预料到的。我怎么能'模仿'this this.state.textValue?或者这是完全错误的做法?

1 个答案:

答案 0 :(得分:0)

对于遇到此问题的其他任何人(我想OP现已解决了这个问题)-如果使用enzyme,则可以直接在组件上调用setState:

// assuming props and mockState are set in a beforeEach()
it('adds state to the component', () => {
  const myComponent = shallow(<MyComponent {...props} />);
  myComponent.setState({ ...mockState });
  const instance = myComponent.instance();
  expect(instance.state).toEqual(mockState);

  // you can then directly call instance methods - e.g. mocking 
  // previous props/state to test changes are handled as expected
  instance.componentDidUpdate(prevProps, prevMockState);
});

请注意,根据您的要求,您可能需要使用mount()而不是shallow()