我正在撰寫一個測驗來檢查在執行回呼時是否呼叫了一個方法。但是,它讓我出現了這個錯誤。
expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
Received has value: undefined
根據Jest 自動類模擬,添加該行jest.mock(...)應該足以獲得模擬類,但似乎我在這里遺漏了一些東西。
這是我的測驗檔案:
import { render, fireEvent } from "@testing-library/react";
import Grid from "../../components/Grid";
import DetectFibonacciUseCase from "../../useCases/DetectFibonacciUseCase";
jest.mock("../../useCases/DetectFibonacciUseCase");
describe("GridComponent", () => {
test("Should've called the run method when the callback is executed", () => {
const { getByTestId } = render(<Grid />);
const firstCellButton = getByTestId("cell-testid-0-0");
fireEvent.click(firstCellButton);
expect(DetectFibonacciUseCase.run).toHaveBeenCalled();
});
});
回呼函式看起來像這樣,它實際上正在執行:
const calculateNewValues = (row, column) => {
const updatedCells = cells.map((cell) => {
cell.value = cell.row === row || cell.column === column
? cell.value 1
: cell.value;
cell.color = cell.row === row || cell.column === column ? ColorConstants.yellow : cell.color;
return cell;
});
const detectFibonacciUseCase = new DetectFibonacciUseCase(
MINIMUM_CONSECUTIVE_APPAREANCES
);
const cellsWithFibonacci = detectFibonacciUseCase.run(updatedCells);
cellsWithFibonacci.forEach((cellWithFibonacci) => {
const cellToUpdateIndex = updatedCells.findIndex(
(cell) =>
cell.row === cellWithFibonacci.row &&
cell.column === cellWithFibonacci.column
);
updatedCells[cellToUpdateIndex].color = ColorConstants.green;
updatedCells[cellToUpdateIndex].value = 1;
});
setCells(updatedCells);
removeColorsAfterTimeout(updatedCells);
};
我也嘗試使用該mockImplementation方法,但根本沒有運氣。任何建議都很受歡迎。
Jest 版本:26.6.0 React 版本:17.0.2 React-testing-library 版本:^12.1.2
uj5u.com熱心網友回復:
該run方法由DetectFibonacciUseCase類的實體呼叫,而不是由類本身呼叫。
雖然 Jest 自動模擬將按預期作業,但您需要訪問模擬類實體以檢查該run函式是否已被呼叫。
const mockDetectFibonacciUseCaseInstance = DetectFibonacciUseCase.mock.instances[0];
expect(mockDetectFibonacciUseCaseInstance.run).toHaveBeenCalled();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/324859.html
標籤:javascript 反应 单元测试 玩笑 反应测试库
