Enzyme的simulate()不会改变onChange事件的输出

时间:2017-09-28 21:53:27

标签: javascript reactjs enzyme jest

我有这个组件和一些测试:

从'react'导入React;     从'prop-types'中导入PropTypes;

function SubList (props) {
    var subways = ['', '1', '2', '3', '4', '5', '6', 
    'S', 'A', 'C', 'E', 'B', 'D', 'F', 'M', 'N', 'Q', 'R', 'L', 'G']
    return (
        <select onChange={props.onSubSelect}>
            {
                subways.map(subway =>
                    <option key={subway}>
                        {subway}
                    </option>
                )
            }
        </select>
    )
}
SubList.PropTypes = {
    onSubSelect: React.PropTypes.func.isRequired
};

export default SubList;

试验:

import React from 'react';
import {shallow} from 'enzyme';
import SubList from '../components/SubList';

let subSelectFn, wrapper;

beforeEach(() => {
    subSelectFn = jest.fn();
    wrapper = shallow(<SubList onSubSelect={subSelectFn}/>);
});

afterEach(() => {
    subSelectFn.mockReset();
});

it('should render a list of subways as an dropdown menu', () => {
    expect(wrapper.find('option').length).toBe(20);
});

it('should display the subway line in each `<option>` element', 
() => {
    const secondElement = wrapper.find('option').at(1);
    expect(secondElement.contains('1')).toEqual(true);
});

it('should call `props.onSubSelect` when an `option` is clicked', 
() => {
    // Expect that no calls have been made yet
    expect(subSelectFn.mock.calls.length).toEqual(0);

    // Click the <option>
    wrapper.find('select').simulate('click');

    // Check that the function has been called
    expect(subSelectFn.mock.calls.length).toEqual(1);

    // Check that the function was called with the right arguments
    expect(subSelectFn.mock.calls[0][0]).toEqual('1');
});

测试最后一次测试仍然失败,我非常确定它是expect(subSelectFn.mock.calls.length).toEqual(1);。我也很确定这意味着什么是失败的Enzyme的模拟()。我已经尝试将它传递给第二个('选项')。at('1')因为('option')。first()是空白的,也是('select'),如你所见。我已经看过simulate()在文档中的常见陷阱,并不确定其中一个是否正在发生在我身上?

我在控制台中收到的测试失败的消息是

● should call 'props.onSubSelect' when an 'option' is clicked

expect(received).toEqual(expected)

Expected value to equal:
  1
Received:
  0

3 个答案:

答案 0 :(得分:3)

您正在使用'click'进行模拟。相反,试试这个:

wrapper.find('select').simulate('change', 1);

答案 1 :(得分:2)

@patrick是正确的,我对此感到困惑并且最初使用了不同的事件类型,但正确的是变化。

wrapper.find('select').simulate('change', { target: { value: '1' } });

在组件中,确保为每个选项

设置值属性
<select className="form-control" id="select-box" name="select-box" 
        onChange={(e) => this.handleChange(e.target.value)}>
          <option>Select an option</option>
          {
            this.props.options.map((o, index) => {
              return (
                <option key={index} value={o}>
                  {o}
                </option>
              );
            })
          }
</select>

答案 2 :(得分:0)

我发现以下变体有效:

wrapper.find('select').simulate('change', { subway: '1' });