testing-library/svelte-testing-library

SvelteKit, `browser = false`

colecrouter opened this issue · 6 comments

When reading browser from import { browser } from '$app/environment';, it always is false. Is this intentional? Since it is SvelteKit and not Svelte, I'm not sure if it falls within the scope of this library.

yanick commented

Unless you are running your tests in the browser, it should indeed be false.

Right, but isn't the point of jsdom and happy-dom to test as though its in the browser? Would there be some way to override this behaviour? Or does this need to be injected elsewhere?

As a result, all components that aren't ssr/csr agnostic fail all tests, because they run the opposite of the way they're supposed to.

yanick commented

Right, but isn't the point of jsdom and happy-dom to test as though its in the browser?

jsdom and happy-dom, yes. But that's several steps downstream of svelte and sveltekit rendering.

Would there be some way to override this behaviour? Or does this need to be injected elsewhere?

My first thought would be to mock $app/environment and have it returns a browser set to true

What a simple solution, thank you.

tests/mock.ts

vi.mock('$app/environment', () => {
    return {
        browser: true,
    };
});

vite.config.ts

export default defineConfig(({ mode }) => {
    return {
        test: {
            globals: true,
+            setupFiles: ['./tests/mock.ts'],
        },
    },
}

This seems to do it.

yanick commented

W00t! Excellent!

Thanks for the solution. Works on the esm-env package as well.

https://github.com/benmccann/esm-env

import { expect, test, vi } from 'vitest';

vi.mock('esm-env', () => ({ BROWSER: true }));
<script>
  import { BROWSER } from 'esm-env'; // true
</script>