Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to test events being fired #178

Closed
Tracked by #296
marekdedic opened this issue Dec 3, 2021 · 2 comments · Fixed by testing-library/testing-library-docs#1366
Closed
Tracked by #296

How to test events being fired #178

marekdedic opened this issue Dec 3, 2021 · 2 comments · Fixed by testing-library/testing-library-docs#1366

Comments

@marekdedic
Copy link

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!

@NEO97online
Copy link

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

@marekdedic
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants