How would I test that the handleLogout
function is being fired when the data-test="logout"
button is clicked?
const NavBar = props => {
const handleClick = (e, destination) => {
e.preventDefault();
props.history.push(`/${destination || ""}`);
};
// Test when data-test="logout" is clicked, handleLogout is called.
const loginFormat =
Object.keys(props.userDetails).length === 0 ? (
<Fragment>
<button onClick={e => handleClick(e, "login")}>Login</button>
<button onClick={e => handleClick(e, "register")}>Register</button>
</Fragment>
) : (
// This button
<button data-test="logout" onClick={e => handleLogout(e)}>
Logout
</button>
);
const handleLogout = e => {
e.preventDefault();
props.logoutUser();
handleClick(e);
};
return (
<header className="NavBar">
<h2>PalettePicker</h2>
<form className="navbar-form">{loginFormat}</form>
</header>
);
};
My current attempt:
let mockUserDetails = { username: "steve", id: 123 };
beforeEach(() => {
wrapper = shallow(
<NavBar
userDetails={mockUserDetails}
history={historyMock}
/>
);
});
it("should invoke the handleLogout function when logout is clicked", () => {
const mock = jest.spyOn(wrapper, "handleLogout");
const button = wrapper.find('[data-test="logout"]');
// console.log(button.debug());
button.simulate("click", { preventDefault() {} });
});
I am receiving this error: Cannot spy the handleLogout property because it is not a function; undefined given instead
, so i cant even reach an expect block since the spyOn
is throwing an error... any ideas?