Quantcast
Channel: User Schwern - Stack Overflow
Viewing all articles
Browse latest Browse all 581

Answer by Schwern for If you are using "vi.mock" factory, make sure there are no top level variables inside

$
0
0

From the vi.mock documentation...

vi.mock is hoisted (in other words, moved) to top of the file. It means that whenever you write it (be it inside beforeEach or test), it will actually be called before that.

That means what's really run is this:

import { it, vi, expect } from "vitest";// Mocking database modulevi.mock("../database/database", async (importOriginal) => {  const actualModule = await importOriginal<typeof import("../database/database")>();  return {    ...actualModule,    __esModule: true,    ownerDb: new Kysely<DB>({      dialect: new MysqlDialect({ pool: vi.fn() }),    }),  };});import db from "../database/database";import { DB } from "../types/schema.types";import { Kysely, MysqlDialect } from "kysely";// Test caseit("Get user count", async () => {  const mocks = vi.hoisted(() => ({ query: vi.fn() }));

The block passed to vi.mock cannot see DB. You can use vi.hoisted on the import. Then the import will be hoisted along with the call to vi.mock.

import { it, vi, expect } from "vitest";import db from "../database/database";import { Kysely, MysqlDialect } from "kysely";const { DB } = vi.hoisted(() => await import('../types/schema.types'));

See A Practical Guide to Mocking Svelte Stores with Vitest.


However, hoisting makes the code very difficult to understand and vi.mock is loaded with caveats. Consider using vi.doMock instead. Note that you will have to dynamically import ../database/database.


Viewing all articles
Browse latest Browse all 581

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>