[英]React Jest Testing button click called a function
我對 React 很陌生,希望能夠測試單擊按鈕時是否調用了 function,但是我無法使其正常工作。 我已經嘗試過以下帖子的答案: How to test a function is called in react jest? 和其他人,但無濟於事。
我的組件片段是:
// 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;
}
這是我試圖開始工作的測試,由各種 Stackoverflows 和文章拼湊而成:
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 的任何幫助將不勝感激!
要使酶能夠跟蹤 function 調用,您必須監視該 function,如下所示:
const scrollToTopEventSpy = jest.spyOn(ScrollToTop.prototype, 'scrollToTopEvent);
然后你可以像這樣測試調用:
expect(scrollToTopEventSpy).toHaveBeenCalled();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.