Let's say I have a simple component like this.
import React, { useState } from "react";
const Counter = () => {
const [counter, setCounter] = useState(0);
const incCounter = () => {
setCounter(counter + 1);
};
return (
<>
<p>Counter value is: {counter}</p>
<button className="increment" onClick={incCounter}>
Up
</button>
</>
);
};
export default Counter;
I want to write test cases using jest and enzyme. But counter.instance()
always returns null.
Any help will be greatly appreciated.
import React from "react";
import Counter from "../components/Counter";
import {
mount,
shallow
} from "./enzyme";
describe("Counter", () => {
let counter;
beforeEach(() => {
counter = shallow( < Counter / > );
})
it("calls incCounter function when button is clicked", () => {
console.log(counter)
counter.instance().incCounter = jest.fn();
const incButton = counter.find("button");
incButton.simulate("click");
expect(counter.incCounter).toBeCalled();
})
});