我有一个搜索过滤器组件,里面有一个输入,它连接到redux。
class SearchFilter extends PureComponent {
constructor (props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.state = {
keyword: props.searchKeyword
};
}
handleInputChange (e) {
this.setState({keyword: e.target.value});
this.props.dispatch(SetFiltersValue(...);
}
render () {
const {keyword} = this.state;
return (
<div className="search-w bp3-input-group">
<span className="bp3-icon bp3-icon-search"/>
<input className="bp3-input" value={keyword} type="text" placeholder="Search input" dir="auto" onChange={this.handleInputChange} />
</div>
);
}
}
const mapStateToProps = (_, ownParams) => {...};
export default connect(mapStateToProps)(SearchFilter);
我用jest和enzyme编写了一个测试,当用户输入一个新值时,测试状态更新
import React from "react";
import SearchFilter from "../../dev/components/shared/searchFilter";
import {shallow, mount} from "enzyme";
import configureStore from "redux-mock-store";
describe("Testing Search filter", () => {
const mockStore = configureStore(),
initialStoreState = {
filtersParams: {}
};
let store;
beforeEach(() => {
store = mockStore(initialStoreState);
});
it("Update search field value when user enters a value", () => {
const wrapper = shallow(<SearchFilter store={store}/>).dive(),
searchInput = wrapper.find("input.bp3-input").first();
expect(searchInput).toBeDefined();
const mockedEvent = {
preventDefault () {},
target: { value: "foo" }
};
expect(wrapper.state("keyword")).toEqual("");
searchInput.simulate("change", mockedEvent);
wrapper.update();
expect(wrapper.state("keyword")).toEqual("foo");
});
});
问题是在模拟更改后状态不更新,并且测试总是失败。
我该如何解决这个问题,或者是否有其他方法来测试状态更新?
1条答案
按热度按时间llmtgqce1#
一个完整的测试示例:
index.tsx
:actionCreators.ts
:单元测试:
100%覆盖率的单元测试结果:
React组件快照:
以下是完整的demo:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54587960