I have a simple component like so:
const MyButton = ({ onLinkClick ) => {
const handleClick = e => {
e.preventDefault()
onLinkClick({ href: e.target.href, foo: 'bar', baz: 'quz' }
}
return (
<a href='some-url' onClick={handleClick}>Click me</a>
)
}
And I'm trying to test it like so:
it('calls onLinkClick with right arguments upon click', () => {
const props { onLinkClick: jest.fn() }
const mockEvent = {
preventDefault: () => {}
target: { href: 'foo.com' }
}
render(<MyButton { ...props } />)
fireEvent.click(screen.getByRole('link'), mockEvent)
expect(props.onLinkClick).toHaveBeenCalledTimes(1)
expect(props.onLinkClick).toHaveBeenCalledWith({
href: mockEvent.target.href, // Test fails right here
foo: 'bar',
baz: 'quz',
})
})
I am just trying to test that the right properties are passed to the onLinkClick
function and one of those properties happen to reference e.target.href
.
It expects foo.com
but actually receives https://www.example.com/foo.com
Does anyone know what I did wrong?
It looks like if I pass in a fully qualified domain name (including the trailing slash), it works.
const mockEvent = {
preventDefault: () => {}
target: { href: 'https://www.example.com/' }
}
Simply using foo.com
was being treated as a relative path.