Giter Club home page Giter Club logo

svelte-jester's Introduction

KitDocs

package-badge

Documentation integration for SvelteKit. You can think of it as a VitePress alternative for Svelte.

Demo ScreenShot

โœจ Features

  • ๐Ÿ“ Vite plugin for transforming Markdown files to Svelte components with HMR support.
  • ๐Ÿ“ก Loaders and endpoint handlers for loading Markdown metadata (i.e., title, frontmatter, etc.), and sidebar configurations.
  • ๐ŸŽจ Beautiful pre-designed theme that's inspired by the Tailwind docs.
  • โ™ฟ Accessible menus and popovers with full keyboard support, which are included in the default theme and also exported for your convenience.
  • ๐ŸŒŽ Global components folder that's imported into all Markdown files and also mapped to custom containers (e.g., Button.svelte -> :::button).
  • ๐Ÿงฉ Markdown extensions for header anchors, file links, YAML frontmatter, emojis, custom containers, table of contents, code fences, and importing code snippets.
  • ๐Ÿ–ผ๏ธ Beautiful syntax highlighting with Shiki. This includes pre-designed code blocks that support titles, line highlighting, copy code button and a few other goodies.
  • ๐Ÿ—๏ธ Prebuilt Markdown components for steps, admonitions (i.e., callouts), tabbed links, responsive tables, and yes/no blocks.
  • ๐Ÿ”Ž Algolia search integration that includes a clean default design.

๐Ÿ“– Documentation

You can find our documentation at kitdocs.vercel.app.

โค๏ธ Special Thanks

Thanks to Vercel for graciously providing us an OSS sponsored account for hosting our docs site!

Powered by Vercel

๐Ÿ“ License

KitDocs is MIT licensed.

svelte-jester's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

svelte-jester's Issues

Usage with yarn workspaces

I'm using svelte-jester in a yarn workspace in a larger project and have a svelte.config.js file in the workspace directory. The tests run fine when invoked from the workspace directory but fail if invoked from the root directory of the project because the svelte.config.js file is not found. Moving svelte.config.js to the root directory is not an option. Is there a way to resolve this?

solution

i found the solution. closed it. thx

jest 27 + svelte-jester 2

just tried upgrading jest + svelte-jest with the new release

getting various errors with different configurations.

See linked github actions builds for specifics

Tests present errors about types, inconsistently

Hey! To preface my issue, I am new to Svelte, and so this is my first time jumping through most of these hoops.

Following the Svelte guide for setting up a TypeScript project, I built myself a script to set up a minimal project with a single test for the "Hello World" App component that the default template comes with. I followed the testing setup guide from testing-library, which is what brought me here.

I can run the script to build a new project, cd into it, and run the test with yarn jest, and it passes. If I then edit the test file in any way, say adding an extra 'expect(5).toEqual(5);`, then the tests blow up at me and tell me that they "cannot find name 'test'" and ask me if I forgot to install type definitions.

Screen Shot 2020-09-23 at 7 17 41 PM

If I remove the "offending" change, the issue persists. If I also delete the node_modules folder and run yarn install again, then the test will pass.

Here is a repository with an app fresh off the presses from the script, which I was just able to reproduce the issue with on my system (macOS 10.15.5).

I would hugely appreciate any help that you are able to give. Please let me know if you need any more information!

Use with rollup plugins

This may not be svelte-jester specific so sorry if this isn't relevant, but I am using @rollup/plugin-alias so that I can import files without defining paths relative to the cwd (eg. import Button from "$components/Button.svelte"). Is it possible to provide this alias plugin & config to svelte-jester so that tests can also resolve these files correctly?

Fail to run preprocess on Windows machine

Looks like plugin fails to run preprocess on windows machines.

How to reproduce:

On Windows, with node 14.17.0 installed run following

npx degit dceddia/svelte-typescript-jest tests-fail-to-load-on-win
cd tests-fail-to-load-on-win
npm i svelte-jester@latest
npm run test

Expected:

We should see 2 passed tests.

Actual:

> [email protected] test D:\_Svelte\tests-fail-to-load-on-win
> jest

internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'D:\_Svelte\tests-fail-to-load-on-win\node_modules\svelte\compiler' imported from D:\_Svelte\tests-fail-to-load-on-win\node_modules\svelte-jester\src\preprocess.js
Did you mean to import svelte/compiler.js?
    at finalizeResolution (internal/modules/esm/resolve.js:276:11)
    at moduleResolve (internal/modules/esm/resolve.js:699:10)
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)
    at Loader.resolve (internal/modules/esm/loader.js:88:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:241:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:56:40)
    at link (internal/modules/esm/module_job.js:55:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
 1: 00007FF65D7D3E0F napi_wrap+108911
 2: 00007FF65D777E16 v8::base::CPU::has_sse+61910
 3: 00007FF65D77A859 node::OnFatalError+7273
 4: 00007FF65DFFDDCF v8::internal::Builtins::builtin_handle+321711
 5: 00007FF65DFFD364 v8::internal::Builtins::builtin_handle+319044
 6: 00007FF65DFFD657 v8::internal::Builtins::builtin_handle+319799
 7: 00007FF65DFFD4A3 v8::internal::Builtins::builtin_handle+319363
 8: 00007FF65E0D9C8D v8::internal::SetupIsolateDelegate::SetupHeap+465453
 9: 00007FF65E072092 v8::internal::SetupIsolateDelegate::SetupHeap+40498
10: 00007FF65E09F208 v8::internal::SetupIsolateDelegate::SetupHeap+225192
11: 00007FF65E11BFDE v8::internal::SetupIsolateDelegate::SetupHeap+736638
12: 00007FF65E092458 v8::internal::SetupIsolateDelegate::SetupHeap+172536
13: 00007FF65E06FC3C v8::internal::SetupIsolateDelegate::SetupHeap+31196
14: 00007FF65DF3FB7F v8::internal::Execution::CallWasm+1839
15: 00007FF65DF3FC8B v8::internal::Execution::CallWasm+2107
16: 00007FF65DF406CA v8::internal::Execution::TryCall+378
17: 00007FF65DF20CE5 v8::internal::MicrotaskQueue::RunMicrotasks+501
18: 00007FF65DF20A40 v8::internal::MicrotaskQueue::PerformCheckpoint+32
19: 00007FF65D800B40 node::CallbackScope::~CallbackScope+672
20: 00007FF65D80090E node::CallbackScope::~CallbackScope+110
21: 00007FF65D7611D0 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfBucketsOffset+199056
22: 00007FF65D834D37 uv_timer_stop+775
23: 00007FF65D83152B uv_async_send+331
24: 00007FF65D830CBC uv_loop_init+1292
25: 00007FF65D830E5A uv_run+202
26: 00007FF65D732CD5 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfBucketsOffset+9365
27: 00007FF65D7A6F37 node::Start+311
28: 00007FF65D60677C RC4_options+339580
29: 00007FF65E5C874C v8::internal::compiler::RepresentationChanger::Uint32OverflowOperatorFor+152316
30: 00007FFF70387034 BaseThreadInitThunk+20
31: 00007FFF704C2651 RtlUserThreadStart+33

Info

Investigated a bit why this is happening, it seems that inside src/preprocess.js line 4 it attempts to import absolute path that fails on Windows machines. It looks like this is by design in NodeJs as mentioned in issue at comment

Provided solution there is to use url.pathToFileURL(pathToFile) to solve convert file path to URL file protocol for ES loader to find the file for windows as well.

Worth mentioning, older version like 1.1.15

resolving node modules

I have a Svelte component I'd like to test that uses a lodash function. Here is the import it uses:

  import get from 'lodash/get';

The component works fine in a Svelte app. But when I test this component with Jest and svelte-jester, the value of get is undefined. It seems the import fails when run in a test. Is there some additional configuration I need to make this work?

Issue with path to preprocessor when the default shell is cmd.exe

Is it possible to change the single quotes around ${preprocessor} in transformer.js to double quotes? I'm getting an error on my Windows machine when the project dir has a space.

Uncaught Error: Cannot find module 'M:\Projects\Svelte Projects\svelte-card-game\'M:\Projects\Svelte'

FROM

at Object.process (node_modules/svelte-jester/src/transformer.js:15:17)
at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:463:35)
at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:568:40)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:606:25)

I'm unable to test on other shells at the moment, but Node documentation suggests it should be fine. Can anyone confirm this issue?

Regression between 1.8.2 and 2.0.0

When I upgrade to 2.0.0, I get following error

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/sandbox/node_modules/svelte-je
ster/src/svelteconfig' imported from /sandbox/node_modules/svelte-jester/src/transformer.js

Here's the sandbox where this error can be seen.

If I revert svelte-jester to 1.8.2, sandbox gives a different error but the same code works fine in my local system.

Error when using context API in test

Hello,
while trying to test parent child components that use the svelte context API, it looks like parent and child component are using different instances of svelte and that makes it impossible to communicate between them (the parent sets something using setContext but when the child tries to get the value using getContext receives an undefined value).

When building the app for the browser a rollup plugin (@rollup/plugin-node-resolve) mark svelte as an external dependency and every component is using the same Svelte instance.

Is there a way to make jest + Svelte work in a similar way?

"TypeError: regexparam is not a function" when using svelte-spa-router

[I'm copy pasting the issue I submitted on the jest repo, one of the collaborators commented that might be of interest]

๐Ÿ› Bug Report

When I'm testing a svelte component that uses svelte-spa-router route:

import { waitFor, render } from '@testing-library/svelte';
import App from './App.svelte';

it('Should render home', async () => {
    const { container, getByText } = render(App);
    
    await waitFor(() => expect(container.querySelector('h1').textContent).toEqual('Bug'));
})

And I have added the transformIgnorePatterns to jest.config.js:

transformIgnorePatterns: [
        'node_modules/(?!(.*(svelte-spa-router|regexparam))/)',
]

I get this error:

TypeError: regexparam is not a function

Apparently svelte-spa-router imports regexparam.

Found this workaround that fixes the problem by adding moduleNameMapper, but it feels wrong:

moduleNameMapper: {
    "^regexparam$": "<rootDir>/node_modules/regexparam/dist/regexparam.mjs"
}

Which in the case of using pnpm, the path will be:

"<rootDir>/node_modules/.pnpm/[email protected]/node_modules/regexparam/dist/regexparam.mjs"

To Reproduce

Steps to reproduce the behavior:

  • Setup an svelte app
  • Add the config files
  • Use svelte-spa-router to create routes
  • Test the component containing the route created in previous step
  • Run the tests with npm run test

Expected behavior

I expect the test to just work, without needing any workarounds.

Link to repl or repo (highly encouraged)

https://github.com/CIAvash/jest-bug

Do:

  • npm install
  • npm run test

envinfo

System:
    OS: Linux 5.11 Arch Linux
    CPU: (2) x64 Intel(R) Core(TM)2 Duo CPU     E8400  @ 3.00GHz
  Binaries:
    Node: 15.11.0 - /usr/bin/node
    npm: 7.6.2 - /usr/bin/npm
  npmPackages:
    jest: ^26.6.3 => 26.6.3

Bufferoverflow when using postcss with tailwind in the preprocessor config

Hi, I have the postcss configured and when It compiles tailwind, jest seems to run many times in quick succession. After a few seconds I get an error.

spawnSync C:\WINDOWS\system32\cmd.exe ENOBUFS

  at Object.process (node_modules/svelte-jester/src/transformer.js:15:17)
  at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:463:35)
  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:568:40)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:606:25)

svlete.config.js

const sveltePreprocess = require("svelte-preprocess");

module.exports = {
  preprocess: sveltePreprocess({
    postcss: true
  }),
};

postcss.config.js

module.exports = {
  plugins: [require("tailwindcss"), require("autoprefixer")]
}

package.json

"jest": {
   "moduleFileExtensions": [
     "js",
     "json",
     "svelte",
     "ts"
   ],
   "transform": {
     "^.+\\.stories\\.[jt]sx?$": "<rootDir>node_modules/@storybook/addon-storyshots/injectFileName",
      "^.+\\.js$": "babel-jest",
     "^.+\\.svelte$": ["svelte-jester", { "preprocess": true } ],
     "^.+\\.ts$": "ts-jest",
     "^.+\\.css$": "jest-transform-css"
   },
   "setupFilesAfterEnv": [
     "@testing-library/jest-dom/extend-expect"
   ],
   "cacheDirectory": "node_modules/.cache/jest"
 }

Environment

...
    "svelte-jester": "^1.1.5",
    "svelte-preprocess": "^4.2.1",
    "tailwindcss": "^1.7.6",
    "jest-transform-css": "^2.0.0",
...

Provide a sample test that works with the default "demo-app" installation of Sveltekit

Could ya? Would ya?

With standard svelte it would be something like:

import { render } from "@testing-library/svelte";
import App from "../App.svelte";

test("should render", () => {
  const results = render(App, { props: { name: "world" } });

  expect(() => results.getByText("Hello world!")).not.toThrow();
});

But for SvelteKit, there's no App.svelte file, and the entrypoints are in the routes folder, so I tried something like this:

import { render } from '@testing-library/svelte';
import App from '../routes/index.svelte';

test('should render', () => {
  const results = render(App, { props: { name: 'world' } });
  console.log('results', results);
  expect(() => results.getByText('Hello world!')).not.toThrow();
});

But that gives errors like this:

    Cannot find module '$lib/Counter/index.svelte' from 'src/routes/index.svelte'

So how does one do it?

Issues when providing options in sveltepreprocessor

Jest is not performing the tests when sveltepreprocessor contains the config values

	preprocess: [
		sveltePreprocess({
			defaults: {
				style: 'postcss',
			},
			postcss: true,
		}),
	],

And If those values are removed it performs the tests but the test fails because most of the components contain the postcss styles.

Screenshot from 2021-04-16 19-30-23

The Header and Card components contain the postcss styles in them, and it's just displays pending for them.

v1.6.0: [ERR_INVALID_ARG_TYPE] when using preprocess

Hi there,

I was just setting up a new project with TS and have gotten a complex error on starting the test (see below). After fiddling a bit, I tried Version 1.5.0 didn't have the issue. Since I could reproduce the issue on 2 machines, I'm quite sure, the cause lies in v1.6.0 of svelte-jester.

These were my steps:

  • update node form version 14.13.0 to version 14.17.0 (LTS) > same error code from the title, but different "details"
  • test on another machine (node v14.15.4) > same error as first machine before update
  • downgrade of svelte-jester to version 1.5.0 > no error, tests work fine on both machines

I created a repo with which the error should be reproducible: https://github.com/Jak-Ch-ll/svelte-jester-error


Error on first machine (Windows 10, node v14.17.0, svelte-jster v1.6.0)

internal/process/promises.js:213
        triggerUncaughtException(err, true /* fromPromise */);
        ^

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received 
an instance of NodeError
    at Socket.Writable.write (internal/streams/writable.js:285:13)
    at file:///D:/data/learning/udemy/svelte-tdd/node_modules/svelte-jester/src/preprocess.js:11:32 {
  code: 'ERR_INVALID_ARG_TYPE'
}
 FAIL  src/pages/SignUpPage.spec.ts
  โ— Test suite failed to run

    Command failed: node --unhandled-rejections=strict --abort-on-uncaught-exception D:\data\learning\udemy\svelte-tdd\node_modules\svelte-jester\src\preprocess.js
    internal/process/promises.js:213
            triggerUncaughtException(err, true /* fromPromise */);
            ^

    TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of NodeError
        at Socket.Writable.write (internal/streams/writable.js:285:13)
        at file:///D:/data/learning/udemy/svelte-tdd/node_modules/svelte-jester/src/preprocess.js:11:32 {
      code: 'ERR_INVALID_ARG_TYPE'
    }


      at Socket.Writable.write (internal/streams/writable.js:285:13)
      at file:/D:/data/learning/udemy/svelte-tdd/node_modules/svelte-jester/src/preprocess.js:11:32 {
        code: 'ERR_INVALID_ARG_TYPE'
      }
      at Object.process (node_modules/svelte-jester/src/transformer.cjs:17:28)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:612:31)
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:758:40)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:815:19)

Error on second machine (Windows 10, node v14.15.4, svelte-jster v1.6.0)

internal/process/promises.js:213
        triggerUncaughtException(err, true /* fromPromise */);
        ^

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of NodeError
    at Socket.Writable.write (internal/streams/writable.js:285:13)
    at file:///C:/Users/J.c/Documents/learning/svelte-tdd/node_modules/svelte-jester/src/preprocess.js:11:32 {
  code: 'ERR_INVALID_ARG_TYPE'
}
 1: 00007FF7BCC8058F napi_wrap+109311
 2: 00007FF7BCC252B6 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfElementsOffset+33302
 3: 00007FF7BCC27BB9 node::OnFatalError+7257
 4: 00007FF7BD49E72F v8::internal::Builtins::builtin_handle+321471
 5: 00007FF7BD49DCC4 v8::internal::Builtins::builtin_handle+318804
 6: 00007FF7BD49DFB7 v8::internal::Builtins::builtin_handle+319559
 7: 00007FF7BD49DE03 v8::internal::Builtins::builtin_handle+319123
 8: 00007FF7BD579F9D v8::internal::SetupIsolateDelegate::SetupHeap+464173
 9: 00007FF7BD5128A2 v8::internal::SetupIsolateDelegate::SetupHeap+40498
10: 00007FF7BD5128A2 v8::internal::SetupIsolateDelegate::SetupHeap+40498
11: 00007FF7BD51055E v8::internal::SetupIsolateDelegate::SetupHeap+31470
12: 00007FF7BD51014C v8::internal::SetupIsolateDelegate::SetupHeap+30428
13: 00007FF7BD3E0631 v8::internal::Execution::CallWasm+1649
14: 00007FF7BD3DFE9F v8::internal::Execution::Call+191
15: 00007FF7BD4CB7E7 v8::Function::Call+615
16: 00007FF7BCCA42DD node::CallbackScope::~CallbackScope+861
17: 00007FF7BCCA3FEE node::CallbackScope::~CallbackScope+110
18: 00007FF7BCC0EA38 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfBucketsOffset+199704
19: 00007FF7BCCD8017 uv_timer_stop+775
20: 00007FF7BCCD484B uv_async_send+331
21: 00007FF7BCCD3FDC uv_loop_init+1292
22: 00007FF7BCCD417A uv_run+202
23: 00007FF7BCBE02B5 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfBucketsOffset+9365
24: 00007FF7BCC53A17 node::Start+311
25: 00007FF7BCAB686C RC4_options+339820
26: 00007FF7BDA5604C v8::internal::compiler::RepresentationChanger::Uint32OverflowOperatorFor+153532
27: 00007FFE42997034 BaseThreadInitThunk+20
28: 00007FFE447E2651 RtlUserThreadStart+33
 FAIL  src/pages/SignUpPage.spec.ts
  โ— Test suite failed to run

    Command failed: node --unhandled-rejections=strict --abort-on-uncaught-exception C:\Users\J.c\Documents\learning\svelte-tdd\node_modules\svelte-jester\src\preprocess.js
    internal/process/promises.js:213
            triggerUncaughtException(err, true /* fromPromise */);
            ^

    TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of NodeError
        at Socket.Writable.write (internal/streams/writable.js:285:13)
        at file:///C:/Users/J.c/Documents/learning/svelte-tdd/node_modules/svelte-jester/src/preprocess.js:11:32 {
      code: 'ERR_INVALID_ARG_TYPE'
    }
     1: 00007FF7BCC8058F napi_wrap+109311
     2: 00007FF7BCC252B6 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfElementsOffset+33302
     3: 00007FF7BCC27BB9 node::OnFatalError+7257
     4: 00007FF7BD49E72F v8::internal::Builtins::builtin_handle+321471
     5: 00007FF7BD49DCC4 v8::internal::Builtins::builtin_handle+318804
     6: 00007FF7BD49DFB7 v8::internal::Builtins::builtin_handle+319559
     7: 00007FF7BD49DE03 v8::internal::Builtins::builtin_handle+319123
     8: 00007FF7BD579F9D v8::internal::SetupIsolateDelegate::SetupHeap+464173
     9: 00007FF7BD5128A2 v8::internal::SetupIsolateDelegate::SetupHeap+40498
    10: 00007FF7BD5128A2 v8::internal::SetupIsolateDelegate::SetupHeap+40498
    11: 00007FF7BD51055E v8::internal::SetupIsolateDelegate::SetupHeap+31470
    12: 00007FF7BD51014C v8::internal::SetupIsolateDelegate::SetupHeap+30428
    13: 00007FF7BD3E0631 v8::internal::Execution::CallWasm+1649
    14: 00007FF7BD3DFE9F v8::internal::Execution::Call+191
    15: 00007FF7BD4CB7E7 v8::Function::Call+615
    16: 00007FF7BCCA42DD node::CallbackScope::~CallbackScope+861
    17: 00007FF7BCCA3FEE node::CallbackScope::~CallbackScope+110
    18: 00007FF7BCC0EA38 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfBucketsOffset+199704
    19: 00007FF7BCCD8017 uv_timer_stop+775
    20: 00007FF7BCCD484B uv_async_send+331
    21: 00007FF7BCCD3FDC uv_loop_init+1292
    22: 00007FF7BCCD417A uv_run+202
    23: 00007FF7BCBE02B5 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfBucketsOffset+9365
    24: 00007FF7BCC53A17 node::Start+311
    25: 00007FF7BCAB686C RC4_options+339820
    26: 00007FF7BDA5604C v8::internal::compiler::RepresentationChanger::Uint32OverflowOperatorFor+153532
    27: 00007FFE42997034 BaseThreadInitThunk+20
    28: 00007FFE447E2651 RtlUserThreadStart+33


      at Socket.Writable.write (internal/streams/writable.js:285:13)
      at file:/C:/Users/J.c/Documents/learning/svelte-tdd/node_modules/svelte-jester/src/preprocess.js:11:32 {
        code: 'ERR_INVALID_ARG_TYPE'
      }
       1: 00007FF7BCC8058F napi_wrap+109311
       2: 00007FF7BCC252B6 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfElementsOffset+33302
       3: 00007FF7BCC27BB9 node::OnFatalError+7257
       4: 00007FF7BD49E72F v8::internal::Builtins::builtin_handle+321471
       5: 00007FF7BD49DCC4 v8::internal::Builtins::builtin_handle+318804
       6: 00007FF7BD49DFB7 v8::internal::Builtins::builtin_handle+319559
       7: 00007FF7BD49DE03 v8::internal::Builtins::builtin_handle+319123
      8: 00007FF7BD579F9D v8::internal::SetupIsolateDelegate::SetupHeap+464173
      9: 00007FF7BD5128A2 v8::internal::SetupIsolateDelegate::SetupHeap+40498
      10: 00007FF7BD5128A2 v8::internal::SetupIsolateDelegate::SetupHeap+40498
      11: 00007FF7BD51055E v8::internal::SetupIsolateDelegate::SetupHeap+31470
      12: 00007FF7BD51014C v8::internal::SetupIsolateDelegate::SetupHeap+30428
      13: 00007FF7BD3E0631 v8::internal::Execution::CallWasm+1649
      14: 00007FF7BD3DFE9F v8::internal::Execution::Call+191
      15: 00007FF7BD4CB7E7 v8::Function::Call+615
      16: 00007FF7BCCA42DD node::CallbackScope::~CallbackScope+861
      17: 00007FF7BCCA3FEE node::CallbackScope::~CallbackScope+110
      18: 00007FF7BCC0EA38 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfBucketsOffset+199704
      19: 00007FF7BCCD8017 uv_timer_stop+775
      20: 00007FF7BCCD484B uv_async_send+331
      21: 00007FF7BCCD3FDC uv_loop_init+1292
      22: 00007FF7BCCD417A uv_run+202
      23: 00007FF7BCBE02B5 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfBucketsOffset+9365
      24: 00007FF7BCC53A17 node::Start+311
      25: 00007FF7BCAB686C RC4_options+339820
      26: 00007FF7BDA5604C v8::internal::compiler::RepresentationChanger::Uint32OverflowOperatorFor+153532
      27: 00007FFE42997034 BaseThreadInitThunk+20
      28: 00007FFE447E2651 RtlUserThreadStart+33
      at Object.process (node_modules/svelte-jester/src/transformer.cjs:17:28)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:612:31)
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:758:40)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:815:19)

Tailwind JIT-Mode hangs on all my jest calls

Tailwind introduced a jit-mode https://tailwindcss.com/docs/just-in-time-mode, which starts an asnyc filewatcher. Now during my jest tests, this will get the node process stuck, which is spawned by the preprocess.

Tailwind docs suggest to supply an environment variable TAILWIND_MODE=build or set NODE_ENV=production. I did this, but it had no effect. My tests were still hanging.

I think I found the issue in https://github.com/mihar-22/svelte-jester/blob/2c532aa31380a29274711748c761fc59cde7f512/src/transformer.js#L19 where the env for the new process are created. Here the TAILWIND_MODE or NODE_ENV just get lost, because they are not passed to the process.

I think we have to pass all variables from process.env down to the next command. I will open a PR in the next minutes.

Transformer.js must export a "process" function - jester v2.0.1 jest 27

Hey guys,

I just updated to the new jester version - 2.0.1 and jest 27 and all tests are now failing with the following error:

Jest: synchronous transformer ......\node_modules\svelte-jester\src\transformer.js must export a "process" function.

      at invariant (node_modules/@jest/transform/build/ScriptTransformer.js:1092:11)
      at assertSyncTransformer (node_modules/@jest/transform/build/ScriptTransformer.js:1098:3)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:611:7)
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:758:40)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:815:19)

Here is a sample test - just rendering a static page

import '@testing-library/jest-dom/extend-expect';
import { render, screen } from '@testing-library/svelte';
import Demo from './demo.svelte';

describe('Demo page test', () => {
	test('shows proper heading when rendered', async () => {
		render(Demo);
		expect(screen.getByText('DEMO PAGE')).toBeInTheDocument();
	});
});

I'm running node LTS 14.17.0.

Any ideas?

Thanks

TypeError [ERR_INVALID_ARG_TYPE]

Having trouble running tests, here's a demo repo.

I'm using it with SvelteKit and pnpm on Windows 10.

PS D:\Projects\svelte-component-template> pnpm test

> ~[email protected] test D:\Projects\svelte-component-template
> cross-env NODE_OPTIONS=--experimental-vm-modules jest src --config jest.config.json

(node:25868) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
(node:28608) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
(node:38792) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  src/lib/first/First.test.js
  โ— Test suite failed to run

    TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received an instance of URL

      at node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/svelte-jester/dist/transformer.cjs:80:118

Unable to get Typescript working with many ES modules

I have a typescript Svelte component that makes use of moment.JS, importing like so:

import moment from "moment

It works with my rollup compilation and development server flawlessly. However, when using svelte-jester and using preprocessing, it says that 'moment is not a function'.

Here is my jest configuration:

module.exports = {
    testEnvironment: "jsdom",
    transform: {
        "^.+\\.svelte$": [
            "svelte-jester",
            {
                preprocess: true
            }
        ],
        "^.+\\.js$": "babel-jest",
        "^.+\\.ts$": "ts-jest"
    },
    moduleFileExtensions: ["js", "ts", "svelte"],
    setupFilesAfterEnv: ["./jestSetup.ts"],
    transformIgnorePatterns: ["node_modules/(?!(svelte-typewriter|svelte-flatpickr)/)"],
    moduleNameMapper: {
        "\\.(css|less|scss)$": "identity-obj-proxy"
    },
    testPathIgnorePatterns: ["/lib/", "/node_modules/"]
}

jestSetup.ts:

import "@testing-library/jest-dom";

tsconfig.json (have tried many variants):

{
    "extends": "@tsconfig/svelte/tsconfig.json",
    "include": ["src/**/*", "src/types/*"],
    "exclude": ["node_modules/*", "__sapper__/*", "public/*"],
    "compilerOptions": {
        "types": ["jest", "node"],
        "allowSyntheticDefaultImports": true,
        "target": "ES2019"
    }
}

test output:


    TypeError: moment is not a function

      35 |                 dv[0] = flatpickr.formatDate(dv[0], "Y-m-d")
      36 |             }
    > 37 |             if (
         |             ^
      38 |                 typeof dv[1] != "string" &&
      39 |                 String(new Date(dv[1])) !== "Invalid Date"
      40 |             ) {

      at updateDate (src/components/Options.svelte:37:13)
      at Object.$$self.$$.update (src/components/Options.svelte:26:4)
      at init (node_modules/svelte/internal/index.js:1450:8)
      at new Options (src/components/Options.svelte:1815:3)
      at Array.create_default_slot_5 (src/App.svelte:25:12)
      at create_slot (node_modules/svelte/internal/index.js:65:29)
      at create_fragment (src/components/Sidebar.svelte:19:23)
      at init (node_modules/svelte/internal/index.js:1454:37)
      at new Sidebar (src/components/Sidebar.svelte:122:3)
      at create_fragment (src/App.svelte:377:12)
      at init (node_modules/svelte/internal/index.js:1454:37)
      at new App (src/App.svelte:510:3)
      at Object.render (node_modules/@testing-library/svelte/dist/pure.js:71:21)
      at Object.<anonymous> (tests/integration/Home.spec.ts:5:40)

This isn't the first time I have had trouble with transpiling. There have been issues with getting other Svelte components to work, problems with flatpickr, etc.

Please let me know if there is something I am doing wrong.

Is click event working? Am I doing something wrong?

Thanks for this awesome package.
I'm new to svelte (actually using it on a project while learning simultaneously) and running into testing issue. You can see a reproduction in this repo. I have issues:

  • here. Clicking reset button is supposed to wipe the form clean and I need to assert the form controls are empty, but this is not working. The handler code.

  • here Submitting the form with invalid data should display error notification. This is not hapening.

Can it be that I'm doing something wrong?

Image imports that use typescript alias returns undefined

Given I have the following typescript configuration.

  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/images*": ["./src/images/*"]
    },
    ...
  },

And jest configuration:

{
  rootDir: "src/",
  moduleDirectories: ["node_modules", "src"],
  moduleFileExtensions: ["svelte", "ts", "js"],
  testPathIgnorePatterns: ["/node_modules/", "/dist/"],
  transform: {
    "^.+\\.svelte$": [
      "svelte-jester",
      {
        preprocess: "./svelte.config.js",
      },
    ],
    "^.+\\.js$": "./babel.config.js",
    "^.+\\.ts$": "ts-jest"
  },
  testEnvironment: "jsdom",
  moduleNameMapper: {
      ".*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/file-mock.js"
    },
}

And I import an image in svelte file

<script lang="ts">
  import airplane from "@/images/airplane.png"
</script>

{#if airplane}
  <img src={airplane} />
{/if}

When I run a test to validate an image exists the test fails because image import returns undefined.
However, If I import the image to a typescript file and export it out as part of an object so it can be consumed in the svelte file, then it works.

Any suggestions what this could be?

Unable to compile Svelte components written in TypeScript

This is an issue for unit testing svelte components written in Typescript which now bundles with Svelte.

The svelte-jester compiler works great otherwise but ideally if this could understand TS written components it would make unit testing much easier.

Cannot find module '$app/env'

Greetings!

I have a small svelte application which I'm trying to write unit tests in. I've followed some online guides how to set up jest + svelte, with svelte-jester. It works fine, until I try to test a component/page which imports {browser} from '$app/env'. I then get the following error:

 PASS  src/spec/errorModal.test.js
  โœ“ Shows the correct title prop on render (37 ms)
  โœ“ Clicking close button removes component from dom (12 ms)

 FAIL  src/spec/register.test.js
  โ— Test suite failed to run

    Cannot find module '$app/env' from 'src/routes/register.svelte'

    Require stack:
      src/routes/register.svelte
      src/spec/register.test.js

      1 | <script>
    > 2 | 	import { browser } from '$app/env';
        | 	                ^
      3 | 	import imageSrc from '../../static/faded-doge-light.svg';
      4 | 	import { axiosRequest } from '../stores/Api';
      5 | 	import ErrorModal from '$lib/modals/errorModal.svelte';

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:306:11)
      at Object.<anonymous> (src/routes/register.svelte:2:18)

Test Suites: 1 failed, 1 passed, 2 total

Is there any configuration that I've missed since this does not work?

Here is my jest.config.cjs:

module.exports = {
	transform: {
		'^.+\\.js$': 'babel-jest',
		'^.+\\.svelte$': [
			'svelte-jester',
			{
				preprocess: true
			}
		]
	},
	setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
	moduleFileExtensions: ['js', 'svelte'],
	bail: false,
	verbose: true,
	transformIgnorePatterns: ['node_modules']
};

and my babel.config.cjs:

module.exports = {
	presets: [['@babel/preset-env', { targets: { node: 'current' } }]]
};

Kind regards, Mattias

Phantom file listed in coverage

I have a phantom file showing up in my coverage listing:

-----------------------------------|---------|----------|---------|---------|-------------------
File                               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------------------------------|---------|----------|---------|---------|-------------------
All files                          |    87.5 |        0 |     100 |     100 |                   
 svelte-component/src              |   83.33 |        0 |     100 |     100 |                   
  Component.svelte                 |   83.33 |        0 |     100 |     100 | 5                 
 svelte-component/src/src          |     100 |      100 |     100 |     100 |                   
  Component.svelte                 |     100 |      100 |     100 |     100 |                                 
-----------------------------------|---------|----------|---------|---------|-------------------

The second directory there does not exist. This occurred on both Node.js LTS and Stable. I'm using ESM and my package.json has "type": "module"

jest.config.ts

import type {Config} from '@jest/types';

const config: Config.InitialOptions = {
  collectCoverage: true,
  coveragePathIgnorePatterns: ['/node_modules/', '/test/', '/dist/'],
  extensionsToTreatAsEsm: ['.ts', '.svelte'],
  globals: {
    'ts-jest': {
      diagnostics: false,
      isolatedModules: true,
      useESM: true,
    },
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'svelte'],
  setupFilesAfterEnv: ['@testing-library/jest-dom'],
  testEnvironment: 'node',
  testRegex: '(/test/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  testURL: 'http://localhost/',
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
    '^.+\\.svelte$': [
      'svelte-jester',
      {
        preprocess: './svelte.config.js',
      },
    ],
  },
};

export default config;

svelte.config.js

import preprocess from 'svelte-preprocess';

export default {
  preprocess: preprocess(),
};

tsconfig.json: This is effectively just for jest since svelte-component/tsconfig.json exists and extends the svelte preset (this is a multi-package monorepo).

{
  "compilerOptions": {
    "esModuleInterop": true,
    "isolatedModules": true,
    "module": "es2020",
    "moduleResolution": "node",
    "target": "es2020"
  },
  "ts-node": {
    "moduleTypes": {
      "jest.config.ts": "cjs"
    },
    "transpileOnly": true
  }
}

command: NODE_OPTIONS=--experimental-vm-modules npx jest -i --env jsdom

Relevant dev dependencies:

{
  "devDependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/svelte": "^3.0.3",
    "@tsconfig/svelte": "^2.0.1",
    "@types/jest": "^26.0.24",
    "@types/node": "^16.4.5",
    "jest": "^27.0.6",
    "svelte": "^3.41.0",
    "svelte-jester": "^2.0.1",
    "svelte-preprocess": "^4.7.4",
    "ts-jest": "^27.0.4",
    "ts-node": "^10.1.0",
    "typescript": "^4.3.5"
  }
}

Is there any way to get rid of that? It really clutters up the coverage outputs.

Jest fails to load svelte libraries

I'll be forward with this, I have absolutely no idea which project I should be posting this in, but I feel like I probably should start somewhere, so I'll go here.

I'm trying to get a svelte project setup. It is currently very minimal, and uses YRV (svelte app router).

I have jest, babel-jest, svelte-jester, @babel/core and @babel/preset-env all installed.

jest.config.js

module.exports = {
  transform: {
    "^.+\\.js$": "babel-jest",
    "^.+\\.svelte$": "svelte-jester"
  },
  moduleFileExtensions: [
    'js',
    'svelte'
  ]
};

babel.config.js

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current'
        }
      }
    ]
  ]
}

When I started trying to test I was running into an error:

 Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     โ€ข If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     โ€ข To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     โ€ข If you need a custom transformation specify a "transform" option in your config.
     โ€ข If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    C:\Users\Jim\projects\bill-tracker\front-end\node_modules\.pnpm\[email protected][email protected]\node_modules\yrv\build\index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Router from './lib/Router.svelte';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | <script>
      2 |   import Button from '../components/button.svelte';
    > 3 |   import { Link } from 'yrv';
        |                ^
      4 | </script>
      5 | <form class="login">
      6 |   I am the login form

      at Runtime.createScriptFromCode (node_modules/.pnpm/[email protected]/node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (src/routes/login.svelte:3:16)

Which is obviously rather odd, because I have the transform set in my jest config.

what I've found in testing is that removing imports form a svelte library (like yrv) works just fine, I can run and mount the component in a test, like so:

// very rough example test, but it passes
import { render } from '@testing-library/svelte';
import Navbar from './navbar.svelte';

it('testing', async () => {
  const wrapper = render(Navbar);
  expect(wrapper.getByText('Navigation Navigation')).toBeTruthy();
});

navbar.svelte

<nav class="bg-green-600 text-gray-100 p-3">
  Navigation Navigation
</nav>

To further test this I installed a svelte component I didn't need, svelte-calendar, and modifying my navbar component to pull that component in the test then breaks with the same error (but obviously now pointing to the navbar.svelte component instead of the app.svelte).

Any help would be appreciated; I don't know for sure it's an error with svelte jester, or something with jest, but obviously this is sort of an issue when i can't unit test my components.

Support components mocks

Hello !
I'm testing my components with jest and @testing-library/svelte and I'm trying to mock component imports, to test parent components without child dependencies. I tried various solutions and none seems to do the job ๐Ÿ˜•
Ideally I would like to do something like this (like testing any JavaScript module) :

The component I'm trying to test (ComponentToTest.svelte) :

<script>
	import MyComponent from './MyComponent/MyComponent.svelte';
	export let active = false;
</script>

{#if active}
  <MyComponent />
{/if}
import ComponentToTest from './ComponentToTest.svelte';

// mocks original component file with __mocks__/MyComponent/MyComponent.svelte file
jest.mock('./MyComponent/MyComponent.svelte');

describe('Test', () => {
	test('should render the component', () => {
		const { container, getByText } = render(ComponentToTest, {
   			props: { active: true },
        });
       expect(...);
    })
})

Of course this does not work, I'm getting this error :

TypeError: Cannot read property 'fragment' of undefined

I didn't find documentation about this, can you tell me if it's currently possible to do what I want with svelte-jester ? Or is this something not implemented yet ?

Unrecognized option 'sourcemap' when I connect svelte-jester

Hi @mihar-22 ,

I am looking into svelte-jester for few days now, and managed to configure it, however, it seems that I am failing on the last bit, and it keeps looking for sourcemap option when I connect svelte-jester to transformer.

> jest

 FAIL  tests/Main.test.js
  โ— Test suite failed to run

    Unrecognized option 'sourcemap'

      at Object.keys.forEach.key (node_modules/svelte/src/compiler/compile/index.ts:40:10)
          at Array.forEach (<anonymous>)
      at validate_options (node_modules/svelte/src/compiler/compile/index.ts:34:23)
      at Object.compile (node_modules/svelte/src/compiler/compile/index.ts:65:2)
      at Object.process (node_modules/svelte-jester/src/transformer.js:28:25)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:464:35)
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:569:40)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:607:25)

Test Suites: 1 failed, 1 total

jest.config.js

module.exports = {
	moduleFileExtensions: ['js', 'svelte'],
	testPathIgnorePatterns: ['node_modules'],
	testMatch: ["**/?(*.)+(spec|test).js?(x)"],
	bail: false,
	verbose: true,
	transform: {
		'^.+\\.js$': 'babel-jest',
		'^.+\\.svelte$': ['svelte-jester', {preprocess: false, sourcemap: false,}],

	},
	collectCoverageFrom: [
		"src/*.js",
		"src/*.svelte",
	],
	setupFilesAfterEnv: [
		'@testing-library/jest-dom/extend-expect'
	],
	resolver: 'jest-svelte-resolver',
}

babel.config.js

module.exports = {
	presets: [
		[
			'@babel/preset-env',
			{
				targets: {
					node: 'current',
				},
			},
		],
	],
	plugins: [
		'@babel/plugin-syntax-dynamic-import',
		[
			'@babel/plugin-transform-runtime',
			{
				useESModules: true
			}
		]
	]
}

main.test.js

import '@testing-library/jest-dom/extend-expect'
import { render } from '@testing-library/svelte'
import Main from '../src/Main.svelte';


test('The component should exist', () => {
	const { container, getByText } = render(Main, {
		props: {
			a: 'test',
			b: 'test'
		},
	});
	expect(container).toBeTruthy();
});

"Don't know how to turn this value into a node" error from babel

X-posted from #28:

Hate to be a party pooper but started using 1.3.1 and I'm now seeing "don't know how to turn this value into a node" from babel for one of my svelte files.

Here's the svelte file

<!-- NoResource.svelte -->
<script lang="ts">
  import Tumbleweed from './Tumbleweed.svelte';
</script>

<div class="h-full w-full flex flex-col justify-center items-center">
  <p class="snapshot-text text-4xl text-center font-semibold opacity-40 mb-6">
    Resource Does Not Exist
  </p>
  <div class="h-2/6 w-full opacity-40">
    <Tumbleweed />
  </div>
</div>

<style>
  .snapshot-text {
    font-family: 'Balsamiq Sans', cursive;
  }
</style>

Error stack trace

 /home/juzerzarif/Documents/terra-wdio-helper/src/webview-ui/common/NoResource.svelte: don't know how to turn this value into a node

      at valueToNode (node_modules/@babel/types/lib/converters/valueToNode.js:90:9)
      at Object.valueToNode (node_modules/@babel/types/lib/converters/valueToNode.js:84:58)
      at Object.exit (node_modules/istanbul-lib-instrument/dist/visitor.js:641:30)
      at PluginPass.exit (node_modules/babel-plugin-istanbul/lib/index.js:158:38)
      at newFn (node_modules/@babel/traverse/lib/visitors.js:175:21)
      at NodePath._call (node_modules/@babel/traverse/lib/path/context.js:55:20)
      at NodePath.call (node_modules/@babel/traverse/lib/path/context.js:42:17)
      at NodePath.visit (node_modules/@babel/traverse/lib/path/context.js:101:8)
      at TraversalContext.visitQueue (node_modules/@babel/traverse/lib/context.js:116:16)
      at TraversalContext.visitSingle (node_modules/@babel/traverse/lib/context.js:85:19)

This is the value that valueToNode receives as argument:

image

Will try to look more into exactly why this file fails and none of the other ones do when I get the time, any help troubleshooting is appreciated!

loading svelte packages from node_modules

Not every Svelte packages are providing CommonJSmodules needed by Jest.

Examples:
svelte-select: provides es, mjs modules and the svelte component
svelte-calendar: provides only the svelte component.

Is there something I can do to tell jest that it has to look for the svelte component when it comes from node_modules?

import Select from 'svelte-select';
import * as CommonJSSelect from 'svelte-select';
const SelectComponent = Select || CommonJSSelect; // issues with jest, needs CommonJS

Run the svelte code through babel

I'm using svelte-jester successfully to test my svelte app with testing-library. Love it!

However mocking svelte components is so far something that I have not figured out. I am trying to mock svelte-select in this instance but it is something that will come up time and again while testing.

I am currently trying to use babel-plugin-rewire-exports which I can get working for any js module imports but not the svelte ones. I figure it's only a case of running the compiled code produced from svelte-jester through babel but I'm not sure how to do that. Any ideas?

jestOptions?.transformerConfig Unexpected token '.'

I started a new project with SvelteKit and typescript enabled.
I added the following to my jest config:

{
    "preset": "ts-jest/presets/default-esm",
    "globals": {
        "ts-jest": {
            "useESM": true
        }
    },
    "transform": {
        "^.+\\.js$": "babel-jest",
        "^.+\\.svelte$": [
            "svelte-jester", {
                "preprocess": true
            }
        ],
        "^.+\\.ts$": "ts-jest"
    },
    "moduleFileExtensions": ["js", "svelte", "ts"],
    "setupFilesAfterEnv": ["@testing-library/jest-dom/extend-expect"]
}

I get the error message:

node_modules/svelte-jester/dist/transformer.cjs:83
  const options = jestOptions?.transformerConfig ?? {};
                              ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at requireOrImportModule (/Users/tom/Workspace/brand-reports/node_modules/jest-util/build/requireOrImportModule.js:53:28)
    at /Users/tom/Workspace/brand-reports/node_modules/@jest/transform/build/ScriptTransformer.js:381:73
    at Array.map (<anonymous>)

image

Am I missing some configuration to enable ?.

I'm using node 14

//.babelrc
{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "current"
                }
            }
        ]
    ]
}

Regression in 2.1.2: a transform must export a `process` or `processAsync` function.

Just updated svelte-jester from 2.1.1 to 2.1.2 and now my tests won't run. "TypeError: Jest: a transform must export a process or processAsync function." Reverting back to 2.1.1 makes the tests run again.

I inserted some console.log calls into the loadTransformers() function from jest-transform and found that it ran three times. The first two times, it went through this block, but the third time it didn't:

if (typeof transformer.createTransformer === 'function') {
  transformer = transformer.createTransformer(transformerConfig);
}

I inserted console.log(transformer) calls before and after that block, and got the following:

First pass

Before:

{
  canInstrument: true,
  getCacheKey: [Function: getCacheKey],
  getCacheKeyAsync: [AsyncFunction: getCacheKeyAsync],
  process: [Function: process],
  processAsync: [AsyncFunction: processAsync],
  createTransformer: [Function: createTransformer]
}

After:

{
  canInstrument: true,
  getCacheKey: [Function: getCacheKey],
  getCacheKeyAsync: [AsyncFunction: getCacheKeyAsync],
  process: [Function: process],
  processAsync: [AsyncFunction: processAsync]
}

Second pass

Before:

{ createTransformer: [Function: createTransformer] }

After:

TsJestTransformer {
  _depGraphs: Map(0) {},
  _watchMode: false,
  _logger: [Function: log] {
    child: [Function (anonymous)],
    wrap: [Function (anonymous)],
    trace: [Function (anonymous)],
    debug: [Function: emptyFunction],
    info: [Function (anonymous)],
    warn: [Function (anonymous)],
    error: [Function (anonymous)],
    fatal: [Function (anonymous)]
  },
  getCacheKey: [Function: bound ],
  process: [Function: bound ]
}

Third pass

Before:

[Function: createTransformer]

After:

[Function: createTransformer]

I don't know why on the third pass, the transformer value is the createTransformer function instead of having a createTrasnformer property (i.e. it should be { createTransformer: [Function: createTransformer] } at that point). Being unfamiliar with the Jest code base, that's as far as I can get easily. But hopefully this will give you some idea of what part of the code might be causing this regression.

Compatibility with Yarn 2 (PnP)

Thanks for this useful library. I was wondering if this works together with Yarn 2 Plug'n'play (pnp)?

I am getting the following error:

 Command failed: node --unhandled-rejections=strict --abort-on-uncaught-exception "C:\Users\Max\repos\goldstack-mega\.yarn\$$virtual\svelte-jester-virtual-411df74ecf\0\cache\svelte-jester-npm-1.3.2-32d0fc490b-4f900c8d1a.zip\node_modules\svelte-jester\src\preprocess.js"
    Uncaught Error: Cannot find module 'C:\Users\Max\repos\goldstack-mega\.yarn\$$virtual\svelte-jester-virtual-411df74ecf\0\cache\svelte-jester-npm-1.3.2-32d0fc490b-4f900c8d1a.zip\node_modules\svelte-jester\src\preprocess.js'

    FROM

      at Object.process (../../../../.yarn/$$virtual/svelte-jester-virtual-411df74ecf/0/cache/svelte-jester-npm-1.3.2-32d0fc490b-4f900c8d1a.zip/node_modules/svelte-jester/src/transformer.js:16:30)

I assume this is caused by the following command in transformer.js#L16 not taking into account the Yarn PnP loader?

    const preprocessResult = execSync(
      `node --unhandled-rejections=strict --abort-on-uncaught-exception "${preprocessor}"`,
      {
        env: { PATH: process.env.PATH, source, filename, svelteConfig },
        maxBuffer: maxBuffer || 10 * 1024 * 1024,
      }
    ).toString();

Jest I think in other places automatically uses the PnP loader.

Preprocessor errors are hidden

Why call preprocessor in a separate process?
If it fails, the standard error remains invisible, stdout returns an empty string and svelte compiler produces an empty component, which just doesn't work and very hard to understand why

TypeError [ERR_INVALID_ARG_TYPE] - Sapper

Hello,

While this might be a duplicate of #72, I prefer to open a new issue as I'm using Sapper instead of SvelteKit, my apologies if it was not the way to go.

Example of traceback (one for each .svelte file)

Failed to collect coverage from <snip>/svelte-jester-bug/src/components/Nav.svelte
ERROR: The "id" argument must be of type string. Received an instance of URL
STACK: TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received an instance of URL
    at validateString (internal/validators.js:124:11)
    at Module.require (internal/modules/cjs/loader.js:954:3)
    at require (internal/modules/cjs/helpers.js:92:18)
    at <snip>/svelte-jester-bug/node_modules/svelte-jester/dist/transformer.cjs:79:118
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

How to reproduce:

  • Degit Sapper npx degit "sveltejs/sapper-template#rollup" my-app
  • Setup Jest with svelte-jester and a simple test; at this point, npx jest should work
  • Add svelte-preprocess, postcss and autoprefixer, change svelte-jester config to use preprocess; npx jest will show errors and fail to add svelte files to the coverage

Or simply clone https://github.com/ko-pp/svelte-jester-bug, run npm i then npx jest

Additional notes:

  • I'm using Linux
  • while the dependencies are outdated on this repo (Svelte 3.17.3 for instance; I wanted to stay as close as possible to the template to reduce chances of me doing something wrong), I have the same problem on my real project with everything up to date

Svelte Jester i18n help

Hi, I'm new to unit testing and I was wondering how to get svelte-jester working with i18n and the router.

When I run my test I get this error.
image

And the router error is..
image

Future Releases

ESM support in Jest is still very experimental https://jestjs.io/docs/ecmascript-modules

Some important things still don't work, like Mocking jestjs/jest#9430

For the new code to work, you need to enabled ESM support in Jest. Which means ALL steps described here https://jestjs.io/docs/ecmascript-modules

This setup can be quite a PITA, because you wil get problems with code written in CJS. This can be a burden to the user, that we enforce the switch to ESM for everyone using this library.

I think we need to refactor this code a little bit more and provide a timeline for different versions. My suggestion is:

  • 1.x -> should still be CJS and support Jest 26
  • 2.x -> should still be CJS, but support Jest 27 + asyncTransformers
  • next -> switch to ESM

What do you think? @benmccann @mihar-22

Incorrect code coverage shown for ts svelte files

Hello, I'm using svelte-jester along with svelte-preprocess to test typescript svelte files but the istanbul code coverage shows uncovered branches that don't exist in the svelte file source code.

Jest config:

export default {
  collectCoverage: true,
  collectCoverageFrom: ['src/**/*.ts', 'src/**/*.svelte'],
  coverageDirectory: 'coverage',
  coveragePathIgnorePatterns: ['src/types'],
  coverageReporters: ['json', 'html', 'text'],
  coverageThreshold: {
    global: {
      statements: -10,
      branches: 90,
      functions: 90,
      lines: 90,
    },
  },
  moduleFileExtensions: ['js', 'ts', 'svelte'],
  moduleNameMapper: {
    '\\.html$': '<rootDir>/__mocks__/htmlMock.ts',
  },
  preset: 'ts-jest',
  roots: [process.cwd()],
  setupFiles: ['mutationobserver-shim'],
  setupFilesAfterEnv: ['./jest.setup.ts'],
  testEnvironment: 'jsdom',
  testMatch: ['**/tests/**/*.test.ts'],
  transform: {
    '^.+\\.svelte$': ['svelte-jester', { preprocess: true }],
    '^.+\\.ts$': 'ts-jest',
  },
};

svelte.config.js:

const sveltePreprocess = require('svelte-preprocess');
const tailwind = require('tailwindcss');
const postcssNested = require('postcss-nested');

module.exports = {
  preprocess: sveltePreprocess({
    postcss: {
      plugins: [tailwind, postcssNested],
    },
  }),
};

Coverage report (html):
image

I'm assuming I've got some gaps in configuration, could someone help troubleshoot how I could get a more accurate coverage report?

Cannot find module './preprocess.js'

First off @mihar-22 @benmccann Thanks for the quick release of 2.1.3! And everyone else who got that through - much appreciated with the quick turnaround. This might be something obvious I'm missing but while the transform export issue has been solved I'm now getting an issue with the preprocess.js file which doesn't seem to exist or be copied into dist. I see that #71 added the command to copy to dist from src/preprocess.js but I'm not seeing it in the final build.

Is there something I need to make sure I'm doing to make this work? I know it's been noted that the fixes for 2.1.3 had been tested in a few places and were working so guessing it's something on my end. Any nudge in the right direction would be great. Thanks!

jest code coverage - uncovered lines

When i use jest --coverage, all tests pass, but some branches do not reach 100% and produce uncovered lines.

Example from a boilerplate of mine.
image

To reproduce a very simple component:

button.svelte

<script lang="ts">
  export let label = '';
</script>

<button>{label}</button>

button.test.ts

import { render } from '@testing-library/svelte'
import Button from '../views/components/button.svelte'

test('button - props', () => {
  const label = 'Click';
  const setLabel = 'New Label';
  const { getByText, component } = render(Button, { label });

  expect(() => getByText(label)).not.toThrow();

  component.label = setLabel;
  expect(() => getByText(setLabel)).not.toThrow();

  component.label = undefined;
  expect(() => getByText('undefined')).toThrow();

  component.label = null;
  expect(() => getByText('null')).toThrow();

  delete component.label;
  expect(() => getByText('null')).toThrow();
})

test('button - no prop', () => {
  global.console.warn = jest.fn()
  const { container } = render(Button);
  expect(container.innerHTML).toBe('<div></div>')
expect(console.warn).toBeCalled()
})

test('button - false prop', () => {
  global.console.warn = jest.fn()
  const {container} = render(Button, { falseProp: false });
  expect(container.innerHTML).toBe('<div></div>')
  expect(console.warn).toBeCalled()
})

It's possible to increase the component's coverage, by introducing the following:
button.svelte

<script lang="ts">
  export let label = '';
  $: cLabel = label || '';
</script>

{#if cLabel}
<button>{cLabel}</button>
{/if}

But even then one else path not taken remains. Which to me makes no sense at that point:
image

Using svelte-jester v1.5.0
Full setup can be found in this repo

Are there plans to support jest ^27?

Hi, I am having some peer dependency issues and looks like I need jest@27 but svelte-jester only currently supports <=26.

Are there plans to bump that up anytime soon?

Thanks in advance for the hard work on the package!

Best,
Jordan

Alternative to loading svelte.config.js ?

Hi, thanks for writing svelte-jester, it seems like the best way to use Jest with Svelte! ๐Ÿ™‚

I noticed that, if a project's package.json declares "type": "module" (new in Node 14), then when running jest it throws an error because it expects an ES module, not a CommonJS module. (See error below.)

I know svelte.config.js is a convention borrowed from svelte-preprocessor, but I wonder if there could be a way to pass the options directly into svelte-jester? This would eliminate the need to load a separate file. Alternatively, it seems that allowing a filename like svelte.config.cjs would also work.

(Interestingly, changing svelte.config.js to use ES module format rather than CommonJS format throws the same error.)

Uncaught Error: Must use import to load ES Module: ~/my-project/svelte.config.js
require() of ES modules is not supported.
require() of ~/my-project/svelte.config.js from ~/my-project/node_modules/cosmiconfig/dist/loaders.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename svelte.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from ~/my-project/package.json.

(FWIW, in case someone is googling this error and happens upon this GitHub issue, I worked around it by forking svelte-jester and avoiding loading the separate file.)

Svelte-kit support

Currently svelte-kit requires "type": "module" to be present in package.json. This does not work with current version of svelte-jester because it uses require under the hood and requires are prohibited with ES modules

Cannot import from context="module"

Hello
I export component specific information from svelte components, but I can not import them in any svelte test using svelte-jester

I am using typescript

<script lang="ts" context="module">
	export const prerender = false;
	export const ARROW_STATE = {
		NONE: 1,
		SHOW: 2,
		DOWN: 4
	};
</script>

// other code from the component

I need to import ARROW_STATE from this component for testing

import Arrow, { ARROW_STATE } from '../Arrow.svelte';
import { render, fireEvent } from '@testing-library/svelte'

// rest of the code 

Error log

   src/lib/components/__test__/Arrow.test.ts:1:17 - error TS2614: Module '"*.svelte"' has no exported member 'ARROW_STATE'. Did you mean to use 'import ARROW_STATE from "*.svelte"' instead?

    1 import Arrow, { ARROW_STATE } from '../Arrow.svelte';

yarn vs npm

I see a package-lock.json which I believe is from npm, but then I see yarn commands in package.json. Can we move everything to npm instead of mixing and matching?

Coverage lines incorrect

I'm using svelte-jester with preprocess -> babel. When I use collect coverage, the line numbers appear to be wrong. Is this something that is fixable within this library?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.