【发布时间】:2020-07-31 10:50:07
【问题描述】:
我正在尝试使用 jest 测试 useDispach。
这是我的组件ItemInput.js:
const ItemInput = ({ value, title, action, type, placeholder }) => {
const dispatch = useDispatch();
return (
<div>
<span data-cy="title">{title}</span>
<Input
type={type}
value={value}
onChange={e =>
dispatch({
type: action,
payload: { value: e.target.value }
})
}
placeholder={placeholder}
data-cy={`item-input-${title}`}
/>
</div>
);
};
这是我的测试:
import React from 'react';
import { mount } from 'enzyme';
import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import ItemInput from '../ItemInput';
const mockStore = configureMockStore([thunk]);
const store = mockStore({});
const setup = () => {
const props = {
action: 'SET_NAME',
value: 'test',
title: 'title',
type: 'text',
placeholder: ''
};
const component = mount(
<Provider store={store}>
<ItemInput {...props} />
</Provider>
);
const input = component.find(`[data-cy="item-input-${props.title}"]`).first();
return {
component,
input,
props
};
};
describe('ItemInput', () => {
it('should render correctly', () => {
const { component } = setup();
expect(component.find('ItemInput').exists()).toEqual(true);
});
it('should call dispach when typing', () => {
const { input, props } = setup();
store.dispatch = jest.fn();
input.simulate('change', { target: { value: 'Jack' } });
expect(store.dispatch).toHaveBeenCalledWith({
type: props.action,
payload: { value: 'Jack' }
});
});
});
预期的行为是 dispatch 被 {type: props.action,payload: { value: 'Jack'}} 调用。
但出现错误:
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: {"payload": {"value": "Jack"}, "type": "SET_NAME"}
Number of calls: 0
60 | input.simulate('change', { target: { value: 'Jack' } });
61 |
> 62 | expect(store.dispatch).toHaveBeenCalledWith({
| ^
63 | type: props.action,
64 | payload: { value: 'Jack' }
65 | });
我认为input.simulate('change', { target: { value: 'Jack' } });有一些问题,它没有触发调度功能。
知道怎么解决吗?
【问题讨论】:
标签: react-redux jestjs react-hooks