Skip to content

Instantly share code, notes, and snippets.

@basilleaf
Last active January 23, 2021 00:31
Show Gist options
  • Save basilleaf/bc5ba62e2dd78a71231aa485a1ce54af to your computer and use it in GitHub Desktop.
Save basilleaf/bc5ba62e2dd78a71231aa485a1ce54af to your computer and use it in GitHub Desktop.
mock any browser event
// example for "scroll"
const simulateEvent = (eventType, e) => {
const listeners = window.addEventListener.mock.calls.filter((call) => call[0] === eventType).map((call) => call[1])
listeners.forEach((listener) => listener(e))
}
beforeEach(() => {
jest.spyOn(window, "addEventListener").mockImplementation(noop)
jest.spyOn(window, "removeEventListener").mockImplementation(noop)
})
it("passes hidden=true on scroll", () => {
wrapper = mountComponent(WrapperComponent, props)
simulateEvent("scroll")
wrapper.update()
expect(wrapper.find("ChildComponent").props().hidden).toEqual(true)
})
// adding/removing the handlers
describe("componentDidMount", () => {
beforeEach(() => {
wrapper = mountComponent(WrapperComponent, props)
})
it("adds a scroll listener for handleWindowScroll", () => {
jest.spyOn(window, "addEventListener")
wrapper.instance().componentDidMount()
expect(window.addEventListener).toHaveBeenCalledWith("scroll", wrapper.instance().handleWindowScroll)
})
})
describe("componentWillUnmount", () => {
it("removes the scroll listener", () => {
jest.spyOn(window, "removeEventListener")
wrapper.instance().componentWillUnmount()
expect(window.removeEventListener).toHaveBeenCalledWith("scroll", wrapper.instance().handleWindowScroll)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment