GithubHelp home page GithubHelp logo

vite-web-test-runner-plugin's Introduction

Material Svelte logo


maintained license npm package
storybook happo.io discord chat


What is material-svelte?

material-svelte is a component-library for svelte implementing the material-design specification.

See it in action on our example application.

See what the components can do in our storybook.

Development Status

  • material-svelte is currently in active development
  • there are still many components missing, but we got a solid foundation
  • APIs of existing components can be considered semi-stable, but should not be considered stable until we hit 2.0.0
  • the topic of theming has yet to be solved
  • the topic of configuration has yet to be solved

Design Goals

  • We aim to be as close as possible to the material design specification as defined by material.io
  • We aim to enable you to quickly and efficiently build your applications
  • We aim to enable you to work with state-of-the-art toolchains. Our primary focus lays on integrating with SvelteKit, Vite, Snowpack
  • We aim for component implementations that follow the Svelte-mindset
  • We aim for being a distinct, svelte-centric implementation. We don't want to be a copy-cat of other libraries (e.g. material-ui, vuetify), which are awesome in their own right

Features

Future

  • We aim to provide you with confidence by having our components fully tested[1]

[1] The foundation is there. But the current test-suite can be considered smoke-test at best.

Installation

SvelteKit

Setup SvelteKit-project

(A full example is available here)

To get started: Create a SvelteKit-project.

❗ Make sure to enable TypeScript-Support.

$ npm init svelte@next
npx: installed 5 in 1.269s

create-svelte version 2.0.0-next.70

Welcome to SvelteKit!

This is beta software; expect bugs and missing features.

If you encounter a problem, open an issue on https://github.com/sveltejs/kit/issues if none exists already.

✔ Which Svelte app template? › Skeleton project
✔ Use TypeScript? … No / Yes
✔ Add ESLint for code linting? … No / Yes
✔ Add Prettier for code formatting? … No / Yes
✔ Copied project files
✔ Added TypeScript support. To use it inside Svelte components, add lang="ts" to the attributes of a script tag.

Setup material-svelte PostCSS-plugin

As we use PostCSS with custom mixins, at-rules etc, you are required to configure svelte to use our PostCSS-plugin.

Install it:

$ npm install --save-dev @material-svelte/postcss-plugin

Enable it in svelte.config.js:

import preprocess from 'svelte-preprocess';
+ import materialPostcss from '@material-svelte/postcss-plugin';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  // Consult https://github.com/sveltejs/svelte-preprocess
  // for more information about preprocessors
-  preprocess: preprocess(),
+  preprocess: preprocess({
+    postcss: {
+      plugins: [
+        materialPostcss(),
+      ],
+    },
+  }),

  kit: {
    // hydrate the <div id="svelte"> element in src/app.html
    target: '#svelte'
  }
};

export default config;

Vite

Setup Vite-project

(A full example is available here)

To get started: Create a Vite-Svelte-project.

❗ Make sure to enable TypeScript-Support.

$ npm init @vitejs/app
✔ Project name: · vite-project
✔ Select a framework: · svelte
✔ Select a variant: · TypeScript

Scaffolding project in /tmp/vite/vite-project...

Done. Now run:

  cd vite-project
  npm install
  npm run dev

Setup material-svelte PostCSS-plugin

As we use PostCSS with custom mixins, at-rules etc, you are required to configure svelte to use our PostCSS-plugin.

Install it:

$ npm install --save-dev @material-svelte/postcss-plugin

Enable it in svelte.config.cjs:

const sveltePreprocess = require('svelte-preprocess')
+ const materialPostcss = require('@material-svelte/postcss-plugin')

module.exports = {
  // Consult https://github.com/sveltejs/svelte-preprocess
  // for more information about preprocessors
-  preprocess: sveltePreprocess()
+  preprocess: sveltePreprocess({
+    postcss: {
+      plugins: [
+        materialPostcss(),
+      ],
+    },
+  })
}

Snowpack

Setup Snowpack-Svelte-project

(A full example is available here)

To get started: Create a Snowpack-Svelte-project.

❗ Make sure to use the TypeScript-enabled app-template.

$ npx create-snowpack-app snowpack-project --template @snowpack/app-template-svelte-typescript
npx: installed 24 in 3.141s

  - Using template @snowpack/app-template-svelte-typescript
  - Creating a new project in /tmp/snowpack-project
  - Installing package dependencies. This might take a couple of minutes.

...

Quickstart:

  cd snowpack-project
  npm start

All Commands:

  npm install      Install your dependencies. (We already ran this one for you!)
  npm start        Start your development server.
  npm run build    Build your website for production.
  npm test         Run your tests.

Setup material-svelte PostCSS-plugin

As we use PostCSS with custom mixins, at-rules etc, you are required to configure svelte to use our PostCSS-plugin.

Install it:

$ npm install --save-dev @material-svelte/postcss-plugin

Enable it in svelte.config.js:

const autoPreprocess = require('svelte-preprocess');
+ const materialPostcss = require('@material-svelte/postcss-plugin')

module.exports = {
  preprocess: autoPreprocess({
    defaults: {
      script: 'typescript',
    },
+    postcss: {
+      plugins: [
+        materialPostcss(),
+      ],
+    },
  }),
};

Usage

Use material-svelte components

You can either install individual component packages (e.g. @material-svelte/button) or the meta-package material-svelte[1]

$ npm install --save-dev @material-svelte/button

Then start using it in your components:

<script lang="ts">
  import { Button } from '@material-svelte/button';
</script>

<Button>Hello World</Button>

[1] We're not completely confident in the meta-package yet. From time-to-time problems arise with transitive-dependencies with individual build-tools.

Contributing

See Contributing Guide

Sponsors

Vercel

vercel logo

Thanks to Vercel for sponsoring this project by allowing it to run deployments for free!

happo.io

happo.io logo

Thanks to happo.io for sponsoring this project by allowing it to run cross-platform, cross-browser screenshot-testing for free!

License

MIT

vite-web-test-runner-plugin's People

Contributors

aaronjensen avatar betaboon avatar ianvs avatar material-svelte-bot avatar scrum avatar sodatea avatar

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

Watchers

 avatar  avatar  avatar  avatar  avatar

vite-web-test-runner-plugin's Issues

Prevent "[vite] connecting..." logs

I think I've gotten my tests running correctly, but for every test, I see:

 🚧 Browser logs:
      [vite] connecting...
      [vite] connected.

Is it possible to silence those? I've tried logLevel: 'silent' in my vite.config.ts, with no luck.

Does not work with @web/test-runner-commands

@web/test-runner-commands enables more advanced plugins like @web/test-runner-visual-regression and it integrates with test-runner by importing a file served by the test-runner server and thus must not be handled by Vite. In snowpack this was easily solved by marking it as an externalPackage but I'm not seeing a similar config property for Vite. https://github.com/snowpackjs/snowpack/pull/1737/files

The logs when trying to use visual regression plugin:

Running tests...

11:19:46 AM [vite] error while updating dependencies:
Error: Build failed with 1 error:
node_modules/@web/test-runner-commands/browser/commands.mjs:2:43: error: Could not resolve "/__web-dev-server__web-socket.js"
    at failureErrorWithLog (/project/node_modules/esbuild/lib/main.js:1466:15)
    at /project/node_modules/esbuild/lib/main.js:1148:28
    at runOnEndCallbacks (/project/node_modules/esbuild/lib/main.js:938:63)
    at buildResponseToResult (/project/node_modules/esbuild/lib/main.js:1146:7)
    at /project/node_modules/esbuild/lib/main.js:1253:14
    at /project/node_modules/esbuild/lib/main.js:629:9
    at handleIncomingPacket (/project/node_modules/esbuild/lib/main.js:726:9)
    at Socket.readFromStdout (/project/node_modules/esbuild/lib/main.js:596:7)
    at Socket.emit (events.js:376:20)
    at addChunk (internal/streams/readable.js:309:12)
11:19:47 AM [vite] Internal server error: Failed to resolve import "/__web-dev-server__web-socket.js" from "node_modules/@web/test-runner-commands/browser/commands.mjs". Does the file exist?
  Plugin: vite:import-analysis
  File: /project/node_modules/@web/test-runner-commands/browser/commands.mjs
  1  |  /* eslint-env browser, es2020 */
  2  |  import { sendMessageWaitForResponse } from '/__web-dev-server__web-socket.js';
     |                                              ^
  3  |  
  4  |  const PARAM_SESSION_ID = 'wtr-session-id';
      at formatError (/project/node_modules/vite/dist/node/chunks/dep-cb562f8f.js:44553:46)
      at TransformContext.error (/project/node_modules/vite/dist/node/chunks/dep-cb562f8f.js:44549:19)
      at normalizeUrl (/project/node_modules/vite/dist/node/chunks/dep-cb562f8f.js:69541:26)
      at async TransformContext.transform (/project/node_modules/vite/dist/node/chunks/dep-cb562f8f.js:69674:57)
      at async Object.transform (/project/node_modules/vite/dist/node/chunks/dep-cb562f8f.js:44751:30)
      at async transformRequest (/project/node_modules/vite/dist/node/chunks/dep-cb562f8f.js:59118:29)
      at async viteTransformMiddleware (/project/node_modules/vite/dist/node/chunks/dep-cb562f8f.js:59256:32)

substitute proxy for redirect

Love the plugin! Thanks for your effort on it!

It works seamlessly for many cases. Recently I found a blocking issue attempting to use it with mockserviceworker to intercept tests. The plugin uses a 302 redirect which prevents mockserviceworker from working. Here:

// redirect requests from web dev server to the vite server for the transpiled code
app.use((ctx, next) => {
  ctx.redirect(`${protocol}://localhost:${port}${ctx.originalUrl}`)
})

I attempted writing a patch that substitutes a proxy for the redirect, but haven't been able to get it to work. Any thoughts on what I'm missing? Here's the replaced code using koa-proxies.

app.use(
  proxy('.*', {
    target: `${protocol}://localhost:${port}`,
    changeOrigin: true,
  }),
)

Thanks!

Edit: Also tried the proxy as middleware per https://modern-web.dev/guides/dev-server/proxy-to-other-servers/#add-a-proxy-to-your-server-config ... no luck yet.

Adam

Tests fail the first time if the build is uncached

I get fairly random errors when I attempt to run tests with cleared vite cache. If I refresh, it's all fine and my tests run and pass no problem.

Here's an example error:

CleanShot 2021-05-03 at 14 46 43@2x

I also sometimes see an error saying that some modules do not have a default export (like assert)

Have you seen this before? Any suggestions?

Thanks!

no such file or directory, open 'node_modules/vite/src/client/env.ts'

My tests all fail with the error message:

[vite] Internal server error: ENOENT: no such file or directory, open 'node_modules/vite/src/client/env.ts'

... unless I go into my node_modules and delete node_modules/vite/dist/client/env.js.map. Is this a problem in vite, or this plugin? I'm brand new to both.

Thanks!

Running tests in docker does not wait for completion

Hi!
First of all, thank you for creating this plugin.

From the command line it works great, but I've tried running the tests with docker, and it actually doesn't wait for the tests to complete. I think this is because the vite dev server startup gives back a 0 exit code. This is just a guess though.

Have you tried this plugin in docker? If so, have you faced the same problem?

"ReferenceError: process is not defined" when using low value for concurrency

I currently have 12 tests and I got this error after test number 10. My config for concurrency is the default value. This is the full error:

Error: Uncaught ReferenceError: process is not defined (http://localhost:8000/__wds-outside-root__/1/node_modules/.pnpm/@[email protected]/node_modules/@vue/shared/dist/shared.esm-bundler.js:472)
at t.onerror (../node_modules/.pnpm/@[email protected]/node_modules/@web/test-runner-mocha/dist/autorun.js:1:326338)

I can temporary escape this error with 2 ways:

  • Set concurrency to some higher value. I did 10 and it was fine.
  • Run only one test file at a time.

web-test-runner integration with vite 3.0

Hi, I found this repo through a link on vitest and on google.

I was looking for the latest vite support (currently 3.x), but quickly realized the code was for the old version.
After hitting myself against the wall for some time, I develop an integration that works with the latest version.

In the spirit of OSS, rather than creating another npm package, I would love to help the maintainer in this repo with the package update if there is the willingness to do so.

For the record, if anyone wants to do the integration in the meantime, here is the code:

// vite-web-test-runner-plugin.js
import { createServer } from 'vite';
import { join, relative } from 'node:path';
import koaConnect from 'koa-connect';
import minimatch from 'minimatch';


/** @typedef { import('@web/test-runner').TestRunnerPlugin } RunnerPlugin */

/**
 * @return { RunnerPlugin }
*/
export default function viteWebTestRunnerPlugin({ testMatch, testRoot = process.cwd(), viteConfigFile } = {}) {
    let viteServer;
    let viteRoot;
    let relativeRoot;

    return {
        name: 'vite-wtr-plugin',
        async serverStart({ app, fileWatcher }) {
            viteServer = await createServer({
                clearScreen: true,
                server: { middlewareMode: true, hmr: false },
                appType: 'custom',
                configFile: viteConfigFile || join(testRoot, 'vite.config.ts')
            });

            viteRoot = viteServer.config.root;

            // This path represents the diff beween the test root and the vite root
            // viteRoot should always be a relative path from the root (ex. testRoot: /root/test vs viteRoot: /root/test/src/module)
            relativeRoot = `/${relative(testRoot, viteRoot)}`;

            // Allow vite to take over most requests
            app.use(koaConnect(viteServer.middlewares));

            // Vite is taking over the handling of URLs, hence we need to forward the watching to the runner
            viteServer.watcher.on('change', (...args) => fileWatcher.emit('change', ...args));

        },
        async transformImport({ source }) {
            const [absSource, ] = source.split('?'); // Remove the queryString otherwise vite will fail resolving
            const relativeSource = absSource.at(0) === '/' ? absSource.substring(1) : absSource;
            for (const match of testMatch) {
                if (minimatch(relativeSource, match)) {
                    const newPath = absSource.replace(relativeRoot, '');
                    return newPath;
                }
            }
        },
        async serverStop() {
            return viteServer.close();
        },
    }
}

Example usage:

// web-test-runner-config.js
import { jasmineTestRunnerConfig } from 'web-test-runner-jasmine';
import viteWebTestRunnerPlugin from './scripts/testing/vite-web-test-runner-plugin.mjs';

const testMatch = ['src/**/*.test.ts'];

export default {
    ...jasmineTestRunnerConfig(),
    files: testMatch,
    nodeResolve: true,
    plugins: [
        viteWebTestRunnerPlugin({ testMatch })
    ],
};

Also, if you want to use commands in WTR you have to tell vite to ignore that endpoint

//vite.config.ts
const webTestRunnerIgnore = (): Plugin => {
    return {
        name: 'web-dev-server',
        resolveId: (id): { external: boolean; id: string } | void => {
            // Vite should not transform the WebSocket route to allow WTR commands to function correctly
            if (id === '/__web-dev-server__web-socket.js') {
                return { external: true, id };
            }
        },
    };
};

export default defineConfig({
  plugins: [webTestRunnerIgnore()]
});

My 2cents: If you are using vite and a web-component framework like lit, using web-test-runner is a superior testing approach rather than using any synthetic DOM implementation like JSDOM or HappyDOM.

Typescript sourcemap

I'm working with typescript with enable sourcemap in my tsconfig.json.
When I throw an error from test, it logged different line number from my ts files.
But when I use @web/dev-server-esbuild line numbers are correct.

web-test-runner.config.mjs

// import { esbuildPlugin } from '@web/dev-server-esbuild';
import vite from 'vite-web-test-runner-plugin';

export default {
  plugins: [
    // esbuildPlugin({ ts: true, target: 'auto' }),
    vite(),
  ],
};

tsconfig.json

{
  "compilerOptions": {
    "module": "es2020",
    "target": "es2019",
    "sourceMap": true,
    "moduleResolution": "node",
    "strict": true,
    "noEmit": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "importsNotUsedAsValues": "error"
  }
}

I'm running with

wtr ./src/**/*.test.ts --node-resolve --coverage

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.