假设我有一个像这样的简单组件。
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;
我想用 jest 和酵素编写测试用例。但counter.instance()
总是返回 null。任何帮助将不胜感激。
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();
})
});