svelte-testing-library icon indicating copy to clipboard operation
svelte-testing-library copied to clipboard

How to test events being fired

Open marekdedic opened this issue 4 years ago • 2 comments

Hi, I'm trying to create a unit test (which testing-library should be able to help me with, as per its FAQ) for a Component which essentially is just a button. However, I found no way to test that an event is fired when I click the button. I've seen #53 which is probably very similar, so to add to this

  • The button doesn't really change on click (I know how to test for that, for example for a "press" animation)
  • The event being fired is the primary function of the button - so that's what I'd like to test (to check that clicking an icon triggers it as well and so on)

I've tried passing the function in the second argument of render, however, it doesn't seem to be called.

Thanks!

marekdedic avatar Dec 03 '21 21:12 marekdedic

Instead of passing the function to render as a prop, use $on to bind a mock function to the component.

This works for me:

it("fires click event", async () => {
	const { component, getByRole } = render(Button)
	const handleClick = jest.fn()
	component.$on("click", handleClick) // Bind mock function to click event using Svelte component API
	const button = getByRole("button")
	fireEvent.click(button)
	expect(handleClick).toHaveBeenCalled()
})

See here for more of svelte's client-side component API which you can make use of for tests: https://svelte.dev/docs#Client-side_component_API

NEO97online avatar Dec 12 '21 23:12 NEO97online

Hi, thanks, that worked!

I am wondering - I am probably not the last person to not know how to do this - maybe add docs for this?

Thanks

marekdedic avatar Dec 13 '21 12:12 marekdedic