How to mock a custom hook with a default export in vitest

I’ve been trying to mock a custom hook but continuously face the same error. I think I am probably missing a fundamental concept about named exports and default exports here.
Consider the following custom hook with pseudo code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const usePiece = (gameMode: string) => {
const [piece, setPiece] = useState<Piece>({
position: { x: 0, y: 0 },
tetromino: TETROMINOES[0].shape,
collided: false,
});
// Rotates the tetromino
const rotate = (matrix: TetrominoShape, direction: number) => {
// Code to rotate the matrix
};
// Piece rotate
const pieceRotate = (stage: StageType, direction: number) => {
// Code to rotate the piece
};
// Updates the position of the piece to the received
// parameters
const updatePiecePosition = ({
x,
y,
collided,
}: {
x: number;
y: number;
collided: boolean;
}) => {
setPiece((prev) => ({
...prev,
position: { x: prev.position.x + x, y: prev.position.y + y },
tetromino: prev.tetromino,
collided,
}));
};
// Resets the piece state. Callback doesn't depend on
// anything because the function is only called once
const resetPiece = useCallback(
(tetromino: TetrominoShape | null) => {
// Code to reset the piece
},
[gameMode]
);
return {
piece,
updatePiecePosition,
resetPiece,
pieceRotate,
};
};
export default usePiece;
</code>
<code>const usePiece = (gameMode: string) => { const [piece, setPiece] = useState<Piece>({ position: { x: 0, y: 0 }, tetromino: TETROMINOES[0].shape, collided: false, }); // Rotates the tetromino const rotate = (matrix: TetrominoShape, direction: number) => { // Code to rotate the matrix }; // Piece rotate const pieceRotate = (stage: StageType, direction: number) => { // Code to rotate the piece }; // Updates the position of the piece to the received // parameters const updatePiecePosition = ({ x, y, collided, }: { x: number; y: number; collided: boolean; }) => { setPiece((prev) => ({ ...prev, position: { x: prev.position.x + x, y: prev.position.y + y }, tetromino: prev.tetromino, collided, })); }; // Resets the piece state. Callback doesn't depend on // anything because the function is only called once const resetPiece = useCallback( (tetromino: TetrominoShape | null) => { // Code to reset the piece }, [gameMode] ); return { piece, updatePiecePosition, resetPiece, pieceRotate, }; }; export default usePiece; </code>
const usePiece = (gameMode: string) => {
  const [piece, setPiece] = useState<Piece>({
    position: { x: 0, y: 0 },
    tetromino: TETROMINOES[0].shape,
    collided: false,
  });

  // Rotates the tetromino
  const rotate = (matrix: TetrominoShape, direction: number) => {
    // Code to rotate the matrix
  };

  // Piece rotate
  const pieceRotate = (stage: StageType, direction: number) => {
    // Code to rotate the piece
  };

  // Updates the position of the piece to the received
  // parameters
  const updatePiecePosition = ({
    x,
    y,
    collided,
  }: {
    x: number;
    y: number;
    collided: boolean;
  }) => {
    setPiece((prev) => ({
      ...prev,
      position: { x: prev.position.x + x, y: prev.position.y + y },
      tetromino: prev.tetromino,
      collided,
    }));
  };


  // Resets the piece state. Callback doesn't depend on
  // anything because the function is only called once
  const resetPiece = useCallback(
    (tetromino: TetrominoShape | null) => {
      // Code to reset the piece
    },
    [gameMode]
  );

  return {
    piece,
    updatePiecePosition,
    resetPiece,
    pieceRotate,
  };
};

export default usePiece;

My attempt at mocking this hook:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
describe("Example test", () => {
beforeEach(() => {
// Mocking usePiece to control the piece's initial position and movement
vi.mock('@hooks/usePiece', () => {
const TEST_STAGE_WIDTH = 6;
return {
default: vi.fn().mockReturnValue({
piece: {
// An 4[] piece on the stage has x position at TEST_STAGE_WIDTH - 2 (as tetromino is a 2X2 matrix)
position: { x: TEST_STAGE_WIDTH - 2, y: 0 },
tetromino: [
[0, 'I'],
[0, 'I'],
],
collided: false,
},
updatePiecePosition: vi.fn(),
resetPiece: vi.fn(),
pieceRotate: vi.fn(),
}),
};
}); });
afterEach(() => {
cleanup;
// vi.clearAllMocks();
vi.restoreAllMocks();
});
})
</code>
<code> describe("Example test", () => { beforeEach(() => { // Mocking usePiece to control the piece's initial position and movement vi.mock('@hooks/usePiece', () => { const TEST_STAGE_WIDTH = 6; return { default: vi.fn().mockReturnValue({ piece: { // An 4[] piece on the stage has x position at TEST_STAGE_WIDTH - 2 (as tetromino is a 2X2 matrix) position: { x: TEST_STAGE_WIDTH - 2, y: 0 }, tetromino: [ [0, 'I'], [0, 'I'], ], collided: false, }, updatePiecePosition: vi.fn(), resetPiece: vi.fn(), pieceRotate: vi.fn(), }), }; }); }); afterEach(() => { cleanup; // vi.clearAllMocks(); vi.restoreAllMocks(); }); }) </code>

describe("Example test", () => {
 beforeEach(() => {
    // Mocking usePiece to control the piece's initial position and movement
     vi.mock('@hooks/usePiece', () => {
      const TEST_STAGE_WIDTH = 6;
      return {
        default: vi.fn().mockReturnValue({
          piece: {
            // An 4[] piece on the stage has x position at TEST_STAGE_WIDTH - 2 (as tetromino is a 2X2 matrix)
            position: { x: TEST_STAGE_WIDTH - 2, y: 0 },
            tetromino: [
              [0, 'I'],
              [0, 'I'],
            ],
            collided: false,
          },
          updatePiecePosition: vi.fn(),
          resetPiece: vi.fn(),
          pieceRotate: vi.fn(),
        }),
      };
    });  });

  afterEach(() => {
    cleanup;
    // vi.clearAllMocks();
    vi.restoreAllMocks();
  });

})

I continuously receive this error.
Error – *Cannot destructure property ‘piece’ of ‘default(…)’ as it is undefined.*


  1. How to mock this custom hook?
  2. What is the difference between the two mock implementations shown below:

Implementation one

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import * as usePiece from '@hooks/usePiece';
vi.mock('@hooks/usePiece');
beforeEach(() => {
usePiece.default = vi.fn().mockReturnValue({
piece: {
// A piece on the stage has x position at TEST_STAGE_WIDTH - 2 (as tetromino is a 2X2 matrix)
position: { x: TEST_STAGE_WIDTH - 2, y: 0 },
tetromino: [
[0, 'I'],
[0, 'I'],
],
collided: false,
},
updatePiecePosition: vi.fn(),
resetPiece: vi.fn(),
pieceRotate: vi.fn(),
});
})
</code>
<code>import * as usePiece from '@hooks/usePiece'; vi.mock('@hooks/usePiece'); beforeEach(() => { usePiece.default = vi.fn().mockReturnValue({ piece: { // A piece on the stage has x position at TEST_STAGE_WIDTH - 2 (as tetromino is a 2X2 matrix) position: { x: TEST_STAGE_WIDTH - 2, y: 0 }, tetromino: [ [0, 'I'], [0, 'I'], ], collided: false, }, updatePiecePosition: vi.fn(), resetPiece: vi.fn(), pieceRotate: vi.fn(), }); }) </code>
import * as usePiece from '@hooks/usePiece';
vi.mock('@hooks/usePiece');

beforeEach(() => {
    usePiece.default = vi.fn().mockReturnValue({
      piece: {
        // A piece on the stage has x position at TEST_STAGE_WIDTH - 2 (as tetromino is a 2X2 matrix)
        position: { x: TEST_STAGE_WIDTH - 2, y: 0 },
        tetromino: [
          [0, 'I'],
          [0, 'I'],
        ],
        collided: false,
      },
      updatePiecePosition: vi.fn(),
      resetPiece: vi.fn(),
      pieceRotate: vi.fn(),
    });
})

and, implementation two

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> vi.mock('@hooks/usePiece', () => {
const TEST_STAGE_WIDTH = 6;
return {
default: vi.fn().mockReturnValue({
piece: {
// An 4[] piece on the stage has x position at TEST_STAGE_WIDTH - 2 (as tetromino is a 2X2 matrix)
position: { x: TEST_STAGE_WIDTH - 2, y: 0 },
tetromino: [
[0, 'I'],
[0, 'I'],
],
collided: false,
},
updatePiecePosition: vi.fn(),
resetPiece: vi.fn(),
pieceRotate: vi.fn(),
}),
};
});
</code>
<code> vi.mock('@hooks/usePiece', () => { const TEST_STAGE_WIDTH = 6; return { default: vi.fn().mockReturnValue({ piece: { // An 4[] piece on the stage has x position at TEST_STAGE_WIDTH - 2 (as tetromino is a 2X2 matrix) position: { x: TEST_STAGE_WIDTH - 2, y: 0 }, tetromino: [ [0, 'I'], [0, 'I'], ], collided: false, }, updatePiecePosition: vi.fn(), resetPiece: vi.fn(), pieceRotate: vi.fn(), }), }; }); </code>
 vi.mock('@hooks/usePiece', () => {
      const TEST_STAGE_WIDTH = 6;
      return {
        default: vi.fn().mockReturnValue({
          piece: {
            // An 4[] piece on the stage has x position at TEST_STAGE_WIDTH - 2 (as tetromino is a 2X2 matrix)
            position: { x: TEST_STAGE_WIDTH - 2, y: 0 },
            tetromino: [
              [0, 'I'],
              [0, 'I'],
            ],
            collided: false,
          },
          updatePiecePosition: vi.fn(),
          resetPiece: vi.fn(),
          pieceRotate: vi.fn(),
        }),
      };
    });
  1. When to use either of the two mock implementations? Would be great, if you can give examples.
  2. What is the meaning of factory in

If factory is defined, all imports will return its result. Vitest calls factory only once and caches results for all subsequent imports until vi.unmock or vi.doUnmock is called.

Quote taken from vitest docs

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật