How to use $app/navigation inside the vitest unit test

476 views Asked by At

Getting this error in files where I am using $app/navigation: Error: Failed to resolve import "$app/navigation" from "src/utils/navigationUtils.js". Does the file exist?.

Here is my setupTests.js file but now getting the same error in this file.

import "@testing-library/jest-dom";
import { vi } from "vitest";
import * as navigation from "$app/navigation";


// Mock SvelteKit runtime module $app/navigation
vi.mock("$app/navigation", () => ({
  afterNavigate: () => {},
  beforeNavigate: () => {},
  disableScrollHandling: () => {},
  goto: () => Promise.resolve(),
  invalidate: () => Promise.resolve(),
  invalidateAll: () => Promise.resolve(),
  prefetch: () => Promise.resolve(),
  prefetchRoutes: () => Promise.resolve(),
}));

After this configration now getting: Error: Failed to resolve import "$app/navigation" from "setupTests.js". Does the file exist?

I have tried to mock the $app/navigation module in setupTests.js file but no success.

1

There are 1 answers

0
possum On BEST ANSWER

For any of the $xxx paths in sveltekit, e.g. $env, $app, $lib, you can create a __mocks__/xxx directory where you can put your navigation mocks to be returned, so something like __mocks__/app in your case. You can then put a navigation.ts with your mock which will be loaded for each of your tests. Then in your vitest.config.ts add

resolve: {
    alias: {
      $app: path.resolve(__dirname, '__mocks__/app')
    }
}

This will allow you to import a version you contrive into your tests.