【发布时间】:2020-08-15 15:38:18
【问题描述】:
我对 React 非常陌生,希望能够测试单击按钮时是否调用了函数,但是我无法使其正常工作。我在How to test a function is called in react jest?等帖子中尝试过答案,但无济于事。
我的组件 sn-p 是:
// Import React core components
import React from 'react';
class ScrollToTop extends React.Component {
/**
* Method to scroll top the top of the page on click
*/
scrollToTopEvent() {
window.scrollTo(0, 0);
};
render() {
return(
<div id="scroll-to-top-container">
{
this.state.showScrollToTop ? (
<button id="scroll-to-top" className="button button-secondary" onClick={ this.scrollToTopEvent }>Scroll to top</button>
) : (
null
)
}
</div>
);
}
export default ScrollToTop;
}
这是我正在尝试开始工作的测试,由各种 Stackoverflow 和文章拼凑而成:
import React from 'react';
import { shallow } from 'enzyme';
import ScrollToTop from "./scroll-to-top";
describe(`Tests the scroll-to-top.js file content`, () => {
const scrollToTop = shallow(<ScrollToTop />);
const instance = scrollToTop.instance();
describe(`Tests scrollToTopEvent`, () => {
it(`should ensure the scrollToTop method was called on button click`, () => {
scrollToTop.setState({ showScrollToTop: true });
jest.spyOn(instance, 'scrollToTopEvent');
const scrollToTopButton = scrollToTop.find(`#scroll-to-top`);
scrollToTopButton.simulate('click');
scrollToTop.update();
expect(instance.scrollToTopEvent).toHaveBeenCalled();
});
});
});
我在控制台中得到的错误是:
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
> 96 | expect(instance.scrollToTopEvent).toHaveBeenCalled();
对于这个 n00b 的任何帮助将不胜感激!
【问题讨论】:
标签: javascript reactjs testing jestjs enzyme