我有以下组件和以下测试。尽管该函数已被模拟,但该测试还是失败。我想知道我应该如何解决它。 “@testing-library/react”:“^14.2.1”和“react”:“^18.2.0”。
import { useCalculator } from "./hooks/useCalculator";
export const CalculatorApp = () => {
const { displayNumber, operation, display, answer, reset } = useCalculator();
return (
<>
<div className="container">
<p>Calculator - React</p>
<div className="calculator">
<div aria-label="display">{displayNumber}</div>
<div className="calculator__keys">
<button
onClick={() => operation("addition")}
aria-label="addition"
>
+
</button>
...
<button aria-label="seven" onClick={() => display(7)}>7</button>
...
</div>
</div>
</div>
</>
);
}
测试
import { fireEvent, render, screen } from "@testing-library/react";
import { CalculatorApp } from "../src/CalculatorApp.jsx";
describe("Component test <CalculatorApp/>", () => {
const mockOperation = jest.fn();
beforeEach(() => jest.clearAllMocks());
test("should call a matematical operation", () => {
render(<CalculatorApp />);
const selectedOperation = screen.getByLabelText("addition");
fireEvent.click(selectedOperation);
expect(mockOperation).toHaveBeenCalled();
expect(mockOperation).toHaveBeenCalledWith("addition");
});
});
您需要模拟钩子以检查该函数是否已被调用。目前,您只是创建一个模拟函数(mockOperation),而没有将其分配给您的钩子。
在您的测试文件中添加以下代码 -
import * as calculator from "./hooks/useCalculator";
// inside test block
const mockOperation = jest.fn();
jest.spyOn(calculator, 'operation').mockImplementation(() => ({operation: mockOperation}));
// your test code
// ...
// now you can write your assertions
expect(mockOperation).toHaveBeenCalled();
expect(mockOperation).toHaveBeenCalledWith("addition");