0

Im trying to mock the api to create my first test using the t3 stack. When I run the test it always tells me that api.transactions is undefined. I have a feeling that it is not configured properly to use the ~/ alias. However given the files below I'm not sure what other config i need. Also I tried to clear the jest cache but it didn't help. I also change the file extension to ../config/api in both test and component file to no avail

ts.config

  "baseUrl": ".",
    "paths": {
      "~/*": ["./src/*"]
    }

jest.config.mjs

const config = {
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  preset: "ts-jest",

  moduleNameMapper: {
    "^~/(.*)$": "<rootDir>/src/$1",
  },

  testEnvironment: "jest-environment-jsdom",
};

The path to the api in the file

import { api } from "~/config/api";

My test mock

// Mocking the api object
jest.mock("~/config/api", () => ({
  transactions: {
    getAllPaginated: {
      useInfiniteQuery: jest.fn().mockReturnValue({
        data: { pages: [] }, // adjust this mock data as per your requirement
      }),
    },
    getTotalByTransactionType: {
      useQuery: jest.fn().mockReturnValue({ data: 0 }), // adjust this mock data as per your requirement
    },
  },
  users: {
    getBalance: {
      useQuery: jest.fn().mockReturnValue({ data: 0 }), // adjust this mock data as per your requirement
    },
  },
}));
describe("Home", () => {
  it("renders a heading", () => {
    const mockSession = {
      expires: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
      user: {
        name: "George Harrison",
        email: "test@test.com",
        image:
          "https://i.pinimg.com/736x/8a/96/a6/8a96a66f28c23d47edcb375913114d66.jpg",
        id: "clikwonjw0006avaldxvcy43m",
      },
    }; // update this to match your session structure

    render(
      <SessionProvider session={mockSession}>
        <Home />
      </SessionProvider>
    );

    const heading = screen.getByRole("heading", {
      name: /welcome to next\.js!/i,
    });

    expect(heading).toBeInTheDocument();
  });
});

failed test

   TypeError: Cannot read properties of undefined (reading 'transactions')
    > 25 |   const { data: txData } = api.transactions.getAllPaginated.useInfiniteQuery(
morraez
  • 3
  • 2

0 Answers0