'spyOn HTMLElement onClick handler

I want to check a link tag clickable or not. So I spyOn HTMLElement.click, but toBeCalled keeps me show false.

Am I doing wrong approach?

Let's assume my link tag looks like below

import MySomeAPI from "./API";
const SomeComponent = () => {


 return (
    <a herf="#" onClick={() => {
     MySomeAPI.call()
     // this is synchronous call
     }}
    >
    text
    </a>
 )
}

const { queryByTestId } = render(<SomeComponent {...props} />);

const linkTag = getByTestId("someLink");
// I checked linkTag gives me HTMLElement


const spy = jest.spyOn(linkTag, "click");
userEvent.click(linkTag);
expect(spy).toBeCalled()

one possible answer could be spyOn MySomeAPI.call, and check it's been called. However, I guess it would be better if I could spy onClick handler entirely.



Solution 1:[1]

You can't spy on it if you can't access it. The onClick is an anonymous function is defined in the function component scope. It's private, you can't get it at the caller's side(in the test case).

Besides, spy on the click event handler and check if it is called or not take more attention to implementation details. This test strategy is not recommended. Instead, you should test the component's behavior.

You should test: When the user clicks the button, what has changed on your component. E.g. What view does the component render?

You can mock side effect methods like MySomeAPI.call and its resolved/rejected value for unit testing. After the API call returns, set the component state and render the corresponding view based on state.

You should test these.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 slideshowp2