如何使用 Jest 测试内部另一个函数的功能?



我刚刚开始学习反应测试并停留在这一刻。

这是我的函数:

private handleCountyItemClick = (
e: React.FormEvent<HTMLButtonElement>
): void => {
const { countries } = this.props.countriesRed;
const selectedId: number = parseFloat(e.currentTarget.dataset.value);
const foundCountry = countries.find(
(country: Country, i: number) => i === selectedId
);
if (foundCountry) {
this.props.CountyItemClick(foundCountry);
this.props.clearInput();
this.setState({
dropdownOpen: false,
fullWidthFullHeightElHeight: 54
});
this.countriesListItems.current.style.height = "";
scrollIt(this.props.countriesRootEl.current, 300, "easeOutQuad", () =>
enableBodyScroll(this.countriesListItems.current)
);
}
};

在那之后,我写了这个测试,我得到错误:

it("should update the count by 1 when invoked by default", () => {
const wrapper = shallow(component);
const instance = wrapper.instance();
instance.handleCountyItemClick({
currentTarget: { dataset: { value: 1 } }
});
});

错误:

TypeError: _this.props.CountyItemClick is not a function

如您所见,在我的函数中,我使用了来自 Redux 的另一个函数,此错误指的是来自 Redux 的函数。我不知道接下来我需要做什么! 我需要做什么?如何进行?

似乎你需要嘲笑你的道具。

let props;
let wrapper;
beforeEach(() => {
props = {
CountyItemClick: jest.fn(),
};
wrapper = shallow(<Component {...props} />);
});
it("should update the count by 1 when invoked by default", () => {
const wrapper = shallow(component);
const instance = wrapper.instance();
instance.handleCountyItemClick({
currentTarget: { dataset: { value: 1 } }
});
expect(props.CountyItemClick).toHaveBeenCalled();
});

最新更新