oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
73.26k stars 2.69k forks source link

bun test cannot find module "$app/environment" in SvelteKit project #5541

Open ChqThomas opened 1 year ago

ChqThomas commented 1 year ago

What version of Bun is running?

1.0.2+37edd5a6e389265738e89265bcbdf2999cb81a49

What platform is your computer?

Linux 5.15.90.1-microsoft-standard-WSL2 x86_64 x86_64

What steps can reproduce the bug?

If one of your tests imports a $app/xxx module from SvelteKit, the bun test command cannot find it.

Follow this steps:

bun create svelte@latest my-app

cd my-app bun install

edit src/index.test.js

import { describe, it, expect } from 'vitest';

// Add this two lines
import { dev } from '$app/environment';
console.log(dev);

describe('sum test', () => {
    it('adds 1 + 2 to equal 3', () => {
        expect(1 + 2).toBe(3);
    });
});

run bun test

What is the expected behavior?

bun test v1.0.2 (37edd5a6)

src/index.test.js:
✓ sum test > adds 1 + 2 to equal 3 [0.01ms]

 1 pass
 0 fail
 1 expect() calls
Ran 1 tests across 1 files. [7.00ms]

What do you see instead?

bun test v1.0.2 (37edd5a6)

src/index.test.js:

error: Cannot find module "$app/environment" from "/xxxxxxxxxx/my-app/src/index.test.js"

 0 pass
 1 fail
Ran 1 tests across 1 files. [7.00ms]

Additional information

The issue is the same with all SvelteKit "$app/xxxx" modules: https://kit.svelte.dev/docs/modules

The same code works with Vitest:

yarn test --run
yarn run v1.22.19
$ vitest --run

 RUN  v0.34.4 /xxxxxxxxxx/my-app

 ✓ src/index.test.js (1)
   ✓ sum test (1)
     ✓ adds 1 + 2 to equal 3

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  10:24:08
   Duration  933ms (transform 15ms, setup 0ms, collect 6ms, tests 2ms, environment 0ms, prepare 51ms)

Done in 1.52s.
Dan1ve commented 6 months ago

It's a bummer that this doesn't work yet, as it prevents Bun from working with (many) SvelteKit projects.

@Jarred-Sumner Is there already a way to define or mock an import for Bun?

For example, it would be sufficient if import { dev } from '$app/environment'; returned a pre-defined constant (false or true).

Jarred-Sumner commented 6 months ago

@Dan1ve here are three ways this can be addressed: 1) mock.module in bun:test 2) virtual modules in Bun.plugin 3) tsconfig.json paths (probably), which Bun also supports

Dan1ve commented 6 months ago

Thanks a lot! I think this should work:

bunfig.toml

[test]
preload = ['./bun-test-plugins.ts']

bun-test-plugins.ts

import { plugin } from "bun";

plugin({
    name: "sveltekit-env",

    setup(build) {
      build.module("$app/environment", () => {
        return {
          exports: {
            dev: false,
          },
          loader: "object",
        };
      });
    },
  });

Now the only remaining problem is that the test runner runs into a segmentation fault, but this is probably unrelated :grin: