gpt4 book ai didi

javascript - Enzyme 的模拟()不会更改 onChange 事件的输出

转载 作者:行者123 更新时间:2023-11-28 13:05:54 25 4
gpt4 key购买 nike

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

从'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 的模拟()失败了。我尝试将第二个 ('option').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

最佳答案

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

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

关于javascript - Enzyme 的模拟()不会更改 onChange 事件的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46478879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com