Skip to content

Commit

Permalink
refactor: replace jest with vitest using a similar approach as vite (#…
Browse files Browse the repository at this point in the history
…337)

* refactor: replace jest with vitest using a similar approach as vite

* ci: check if 2 workers are faster than one

* fix: update unit test

* fix: update ~utils types

* chore: increase connect url timeout

* chore: remove unused await

* chore: try 1 thread

* fix: preserve temp dir on ci, align env names to TEST_

* fix: vitest uses posix paths on windows

* ci: try 4 threads

* fix: return to 1 thread on ci

* ci: use windows-latest again and add node18

* chore: run build tests before serve tests because they are less likely to fail

* refactor: convert test apps to esm, rebuild kit-node app with latest kit, update execa and node-fetch, fix issue with fetch on node18

* fix: revert preprocess-with-vite to cjs hoping it finds stylus correctly again, fetch as util

* fix: force glob to version that includes fix for breaking windows change

* fix: stabilize local tests by limiting max threads, improve untilUpdated utility, remove useless code

* chore: clean up test

Co-authored-by: bluwy <bjornlu.dev@gmail.com>
dominikg and bluwy authored May 16, 2022
1 parent a6a8e00 commit 5b036e8
Showing 60 changed files with 1,045 additions and 3,041 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
@@ -8,5 +8,5 @@ indent_size = 2
charset = utf-8
trim_trailing_whitespace = true

[{**/package.json, **/README.md, docs/**/*.md}]
[{package.json,README.md, docs/**/*.md}]
indent_style = space
19 changes: 3 additions & 16 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -145,23 +145,10 @@ module.exports = {
node: true,
browser: true
},
// Can't extend in overrides: https://github.com/eslint/eslint/issues/8813
// "extends": ["plugin:jest/recommended"]
plugins: ['jest'],
rules: {
'jest/no-disabled-tests': 'warn',
'jest/no-focused-tests': 'error',
'jest/no-identical-title': 'error',
'jest/prefer-to-have-length': 'warn',
'jest/valid-expect': 'error'
}
},
{
files: ['scripts/**'],
env: {
jest: true,
node: true,
browser: false
'node/no-extraneous-import': 'off',
'node/no-missing-import': 'off',
'node/no-unused-import': 'off'
}
},
{
23 changes: 6 additions & 17 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# build and test on linux, windows, mac with node 14, 16, 17
# build and test on linux, windows, mac with node 14, 16, 18
name: CI

on:
@@ -50,7 +50,7 @@ jobs:
if: (${{ success() }} || ${{ failure() }})
run: pnpm audit

# this is the test matrix, it runs with node16 on linux,windows,macos + node14,17 on linux
# this is the test matrix, it runs with node16 on linux,windows,macos + node14,18 on linux
# it is skipped if the build step of the checks job wasn't successful (still runs if lint or audit fail)
test:
needs: checks
@@ -61,10 +61,12 @@ jobs:
fail-fast: false
matrix:
node: [16]
os: [ubuntu-latest, macos-latest, windows-2019]
os: [ubuntu-latest, macos-latest, windows-latest]
include:
- node: 14
os: ubuntu-latest
- node: 18
os: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
@@ -86,7 +88,7 @@ jobs:
- name: build
run: pnpm build:ci
- name: run tests
run: pnpm test:ci
run: pnpm test
- name: archive tests temp directory
if: failure()
shell: bash
@@ -97,17 +99,4 @@ jobs:
name: test-failure-${{github.run_id}}-${{ matrix.os }}-${{ matrix.node }}
path: |
test-temp.tar
temp/serve/jest-results.json
temp/serve/junit.xml
temp/build/jest-results.json
temp/build/junit.xml
pnpm-debug.log
- uses: actions/upload-artifact@v3
if: success()
with:
name: test-success-${{github.run_id}}-${{ matrix.os }}-${{ matrix.node }}
path: |
temp/serve/jest-results.json
temp/serve/junit.xml
temp/build/jest-results.json
temp/build/junit.xml
28 changes: 0 additions & 28 deletions jest.config.js

This file was deleted.

30 changes: 11 additions & 19 deletions package.json
Original file line number Diff line number Diff line change
@@ -5,14 +5,10 @@
"dev": "pnpm --dir packages/vite-plugin-svelte dev",
"build:ci": "pnpm --dir packages/vite-plugin-svelte build:ci",
"build": "pnpm --dir packages/vite-plugin-svelte build",
"test": "run-s test:serve test:build",
"test:serve": "jest",
"test:serve:debug": "cross-env DEBUG=pw:api VITE_DEBUG_SERVE=1 node --inspect-brk ./node_modules/jest/bin/jest --runInBand",
"test:build": "cross-env VITE_TEST_BUILD=1 jest",
"test:build:debug": "cross-env DEBUG=pw:api VITE_TEST_BUILD=1 VITE_PRESERVE_BUILD_ARTIFACTS=1 node --inspect-brk ./node_modules/jest/bin/jest --runInBand",
"test:ci": "run-s test:ci:serve test:ci:build",
"test:ci:serve": "cross-env VITE_PRESERVE_BUILD_ARTIFACTS=1 jest --verbose --no-cache --runInBand --force-exit --ci --json --outputFile=\"temp/serve/jest-results.json\"",
"test:ci:build": "cross-env VITE_TEST_BUILD=1 VITE_PRESERVE_BUILD_ARTIFACTS=1 jest --verbose --no-cache --runInBand --force-exit --ci --json --outputFile=\"temp/build/jest-results.json\"",
"test": "run-s -c test:unit test:build test:serve",
"test:unit": "vitest run",
"test:serve": "vitest run -c vitest.config.e2e.ts",
"test:build": "cross-env TEST_BUILD=1 vitest run -c vitest.config.e2e.ts",
"lint": "eslint --ignore-path .gitignore '**/*.{js,ts,svelte,html,svx,md}'",
"lint:fix": "pnpm lint --fix",
"format": "prettier --ignore-path .gitignore '**/*.{css,scss,svelte,html,js,ts,svx,md}' --check",
@@ -25,7 +21,6 @@
"@changesets/cli": "^2.22.0",
"@svitejs/changesets-changelog-github-compact": "^0.1.1",
"@types/fs-extra": "^9.0.13",
"@types/jest": "^27.5.0",
"@types/node": "^17.0.21",
"@types/semver": "^7.3.9",
"@typescript-eslint/eslint-plugin": "^5.22.0",
@@ -35,36 +30,32 @@
"eslint": "^8.15.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-html": "^6.2.0",
"eslint-plugin-jest": "^26.1.5",
"eslint-plugin-markdown": "^2.2.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-svelte3": "^4.0.0",
"execa": "^5.1.1",
"execa": "^6.1.0",
"fs-extra": "^10.1.0",
"husky": "^7.0.4",
"jest": "^27.5.1",
"jest-environment-node": "^27.5.1",
"jest-junit": "^13.2.0",
"lint-staged": "^12.4.1",
"node-fetch": "^2.6.7",
"node-fetch": "^3.2.4",
"npm-run-all": "^4.1.5",
"playwright-core": "^1.21.1",
"prettier": "^2.6.2",
"prettier-plugin-svelte": "^2.7.0",
"rimraf": "^3.0.2",
"svelte": "^3.48.0",
"ts-jest": "^27.1.4",
"typescript": "^4.6.4",
"vite": "^2.9.8"
"vite": "^2.9.8",
"vitest": "^0.12.6"
},
"lint-staged": {
"*.{js,ts,svelte,html,md,svx}": "eslint --fix",
"*.{css,scss,svelte,html,js,ts,svx,md}": [
"prettier --write"
]
},
"packageManager": "pnpm@7.1.0",
"packageManager": "pnpm@7.1.0",
"engines": {
"pnpm": "^7.1.0",
"yarn": "forbidden, use pnpm",
@@ -73,7 +64,8 @@
},
"pnpm": {
"overrides": {
"@sveltejs/vite-plugin-svelte": "workspace:*"
"@sveltejs/vite-plugin-svelte": "workspace:*",
"glob@^7": "^7.2.3"
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isBuild, findAssetFile } from '../../testUtils';
import { expect, test } from 'vitest';
import { isBuild, findAssetFile, page } from '~utils';

test('should prefix position: sticky for code in source tree', async () => {
const stickyStyle = isBuild
3 changes: 2 additions & 1 deletion packages/e2e-tests/autoprefixer-browerslist/package.json
Original file line number Diff line number Diff line change
@@ -18,5 +18,6 @@
"svelte": "^3.48.0",
"svelte-preprocess": "^4.10.6",
"vite": "^2.9.8"
}
},
"type": "module"
}
10 changes: 0 additions & 10 deletions packages/e2e-tests/autoprefixer-browerslist/svelte.config.cjs

This file was deleted.

12 changes: 12 additions & 0 deletions packages/e2e-tests/autoprefixer-browerslist/svelte.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import sveltePreprocess from 'svelte-preprocess';
import path from 'path';
import { fileURLToPath } from 'url';

export default {
preprocess: sveltePreprocess({
postcss: {
// tests are run on project root and postcss-load-config uses cwd as default so force correct path here
configFilePath: path.join(path.dirname(fileURLToPath(import.meta.url)), 'postcss.config.cjs')
}
})
};
6 changes: 3 additions & 3 deletions packages/e2e-tests/autoprefixer-browerslist/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { svelte } = require('@sveltejs/vite-plugin-svelte');
const { defineConfig } = require('vite');
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';

module.exports = defineConfig(() => {
export default defineConfig(() => {
return {
plugins: [svelte()],
build: {
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { editViteConfig, isBuild } from '../../testUtils';
import { it, expect } from 'vitest';
import { editViteConfig, isBuild, page, e2eServer } from '~utils';

it('should load default config and work', async () => {
expect(e2eServer.logs.server.out).toContain('default svelte config loaded');
3 changes: 2 additions & 1 deletion packages/e2e-tests/configfile-custom/package.json
Original file line number Diff line number Diff line change
@@ -14,5 +14,6 @@
"@sveltejs/vite-plugin-svelte": "workspace:*",
"svelte": "^3.48.0",
"vite": "^2.9.8"
}
},
"type": "module"
}
6 changes: 3 additions & 3 deletions packages/e2e-tests/configfile-custom/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { svelte } = require('@sveltejs/vite-plugin-svelte');
const { defineConfig } = require('vite');
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';

module.exports = defineConfig(() => {
export default defineConfig(() => {
return {
root: './', // ensure custom root works, see https://github.com/sveltejs/vite-plugin-svelte/issues/113
plugins: [svelte()],
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { editViteConfig } from 'testUtils';
import { it, expect } from 'vitest';
import { editViteConfig, page } from '~utils';

it('should load default config and work', async () => {
expect(await page.textContent('h1')).toMatch('Hello world!');
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getText } from '../../testUtils';
import { getText } from '~utils';

test('should render svg', async () => {
expect(await getText('#test-svg')).toBe('Foo bar=bar');
3 changes: 2 additions & 1 deletion packages/e2e-tests/custom-extensions/package.json
Original file line number Diff line number Diff line change
@@ -11,5 +11,6 @@
"@sveltejs/vite-plugin-svelte": "workspace:*",
"svelte": "^3.48.0",
"vite": "^2.9.8"
}
},
"type": "module"
}
6 changes: 3 additions & 3 deletions packages/e2e-tests/custom-extensions/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { svelte } = require('@sveltejs/vite-plugin-svelte');
const { defineConfig } = require('vite');
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';

module.exports = defineConfig(() => {
export default defineConfig(() => {
return {
plugins: [svelte({ extensions: ['.svelte', '.svg'] })],
build: {
13 changes: 7 additions & 6 deletions packages/e2e-tests/e2e-server.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// script to start package.json dev/build/preview scripts with execa for e2e tests
const execa = require('execa');
const treeKill = require('tree-kill');
const fs = require('fs');
const path = require('path');
import { execa } from 'execa';
import treeKill from 'tree-kill';
import fs from 'fs';
import path from 'path';
const isWin = process.platform === 'win32';

async function startedOnPort(serverProcess, port, timeout) {
let id;
let stdoutListener;
@@ -40,7 +41,7 @@ async function startedOnPort(serverProcess, port, timeout) {
});
}

exports.serve = async function serve(root, isBuild, port) {
export async function serve(root, isBuild, port) {
const logDir = path.join(root, 'logs');
const logs = {
server: null,
@@ -157,4 +158,4 @@ exports.serve = async function serve(root, isBuild, port) {
console.error('failed to close server process', e1);
}
}
};
}
2 changes: 1 addition & 1 deletion packages/e2e-tests/env/__tests__/env.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { findAssetFile, isBuild } from 'testUtils';
import { findAssetFile, isBuild } from '~utils';

// can't have no tests for test:serve
it('dummy', () => {});
17 changes: 11 additions & 6 deletions packages/e2e-tests/hmr/__tests__/hmr.spec.ts
Original file line number Diff line number Diff line change
@@ -4,14 +4,17 @@ import {
getEl,
getText,
editFileAndWaitForHmrComplete,
untilUpdated,
untilMatches,
sleep,
getColor,
editFile,
addFile,
removeFile,
editViteConfig
} from '../../testUtils';
editViteConfig,
page,
browserLogs,
viteTestUrl
} from '~utils';

test('should render App', async () => {
expect(await getText('#app-header')).toBe('Test-App');
@@ -30,7 +33,11 @@ test('should render dynamic import', async () => {
const dynamicImportButton = await getEl('#button-import-dynamic');
expect(dynamicImportButton).toBeDefined();
await dynamicImportButton.click();
await untilUpdated(() => getText('#dynamic-import .label'), 'dynamic-import');
await untilMatches(
() => getText('#dynamic-import .label'),
'dynamic-import',
'dynamic import loaded after click'
);
});

test('should not have failed requests', async () => {
@@ -178,7 +185,6 @@ if (!isBuild) {
await updateHmrTest((content) => content.replace('color: red', 'color: green'));
expect(await getColor(`#hmr-test-1 .label`)).toBe('green');
expect(await getText(`#hmr-test-1 .counter`)).toBe('1');
await jest.resetModules();
await editFile('svelte.config.cjs', (content) =>
content
.replace('preprocess-inject', 'preprocess-inject-2')
@@ -197,7 +203,6 @@ if (!isBuild) {
await updateHmrTest((content) => content.replace('color: green', 'color: red'));
expect(await getColor(`#hmr-test-1 .label`)).toBe('red');
expect(await getText(`#hmr-test-1 .counter`)).toBe('1');
await jest.resetModules();
await removeFile('svelte.config.cjs');
await sleep(isWin ? 1000 : 500); // editing config restarts server, give it some time
await page.goto(viteTestUrl, { waitUntil: 'networkidle' });
5 changes: 3 additions & 2 deletions packages/e2e-tests/hmr/package.json
Original file line number Diff line number Diff line change
@@ -13,8 +13,9 @@
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "workspace:*",
"e2e-test-dep-vite-plugins": "workspace:*",
"node-fetch": "^2.6.7",
"node-fetch": "^3.2.4",
"svelte": "^3.48.0",
"vite": "^2.9.8"
}
},
"type": "module"
}
8 changes: 4 additions & 4 deletions packages/e2e-tests/hmr/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const { defineConfig } = require('vite');
const { svelte } = require('@sveltejs/vite-plugin-svelte');
const { transformValidation } = require('e2e-test-dep-vite-plugins');
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';
import { transformValidation } from 'e2e-test-dep-vite-plugins';

module.exports = defineConfig(({ command, mode }) => {
export default defineConfig(({ command, mode }) => {
return {
plugins: [transformValidation(), svelte()],
build: {
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getEl, getText, isBuild } from '../../testUtils';
import { getEl, getText, isBuild } from '~utils';

describe('inspector-kit', () => {
it('should render page', async () => {
7 changes: 1 addition & 6 deletions packages/e2e-tests/inspector-kit/package.json
Original file line number Diff line number Diff line change
@@ -12,10 +12,5 @@
"@sveltejs/kit": "^1.0.0-next.326",
"svelte": "^3.48.0"
},
"type": "module",
"pnpm": {
"overrides": {
"@sveltejs/vite-plugin-svelte": "workspace:*"
}
}
"type": "module"
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getEl, getText, isBuild } from '../../testUtils';
import { getEl, getText, isBuild } from '~utils';

describe('inspector-vite', () => {
it('should render page', async () => {
42 changes: 0 additions & 42 deletions packages/e2e-tests/kit-node/README.md

This file was deleted.

36 changes: 19 additions & 17 deletions packages/e2e-tests/kit-node/__tests__/kit.spec.ts
Original file line number Diff line number Diff line change
@@ -7,11 +7,13 @@ import {
isBuild,
readFileContent,
sleep,
untilUpdated,
waitForNavigation
} from '../../testUtils';
untilMatches,
waitForNavigation,
page,
browserLogs,
fetchPageText
} from '~utils';

import fetch from 'node-fetch';
import path from 'path';

describe('kit-node', () => {
@@ -30,7 +32,7 @@ describe('kit-node', () => {
expect(await page.$eval('#mount', (e) => e['__initialNode'])).toBe(true);

// also get page as text to confirm
const html = await (await fetch(page.url())).text();
const html = await fetchPageText();
expect(html).toMatch('Hello world!');
expect(html).toMatch('SERVER_LOADED');
expect(html).toMatch('BEFORE_MOUNT');
@@ -59,7 +61,7 @@ describe('kit-node', () => {
} else {
// During dev, the CSS is loaded from async chunk and we may have to wait
// when the test runs concurrently.
await untilUpdated(() => getColor('h1'), 'rgb(255, 62, 0)');
await untilMatches(() => getColor('h1'), 'rgb(255, 62, 0)', 'h1 has svelte orange');
}
});

@@ -124,7 +126,7 @@ describe('kit-node', () => {
'<div id="hmr-test">foo</div>\n<!-- HMR-TEMPLATE-INJECT -->'
)
);
await expect(await getText(`#hmr-test`)).toBe('foo');
expect(await getText(`#hmr-test`)).toBe('foo');

// add div 2
expect(await getEl('#hmr-test2')).toBe(null);
@@ -134,14 +136,14 @@ describe('kit-node', () => {
'<div id="hmr-test2">bar</div>\n<!-- HMR-TEMPLATE-INJECT -->'
)
);
await expect(await getText(`#hmr-test`)).toBe('foo');
await expect(await getText(`#hmr-test2`)).toBe('bar');
expect(await getText(`#hmr-test`)).toBe('foo');
expect(await getText(`#hmr-test2`)).toBe('bar');
// remove div 1
await updateIndexSvelte((content) =>
content.replace('<div id="hmr-test">foo</div>\n', '')
);
await expect(await getText(`#hmr-test`)).toBe(null);
await expect(await getText(`#hmr-test2`)).toBe('bar');
expect(await getText(`#hmr-test`)).toBe(null);
expect(await getText(`#hmr-test2`)).toBe('bar');
});

it('should render additional child components', async () => {
@@ -182,7 +184,7 @@ describe('kit-node', () => {
expect(await getText(`#hmr-test2`)).toBe('bar');
await page.reload({ waitUntil: 'networkidle' });
expect(await getColor(`h1`)).toBe('green');
await expect(await getText(`#hmr-test2`)).toBe('bar');
expect(await getText(`#hmr-test2`)).toBe('bar');
});

describe('child component update', () => {
@@ -212,7 +214,7 @@ describe('kit-node', () => {
'<div id="hmr-test3">foo</div>\n<!-- HMR-TEMPLATE-INJECT -->'
)
);
await expect(await getText(`#hmr-test3`)).toBe('foo');
expect(await getText(`#hmr-test3`)).toBe('foo');

// add div 2
expect(await getEl('#hmr-test4')).toBe(null);
@@ -222,14 +224,14 @@ describe('kit-node', () => {
'<div id="hmr-test4">bar</div>\n<!-- HMR-TEMPLATE-INJECT -->'
)
);
await expect(await getText(`#hmr-test3`)).toBe('foo');
await expect(await getText(`#hmr-test4`)).toBe('bar');
expect(await getText(`#hmr-test3`)).toBe('foo');
expect(await getText(`#hmr-test4`)).toBe('bar');
// remove div 1
await updateCounter((content) =>
content.replace('<div id="hmr-test3">foo</div>\n', '')
);
await expect(await getText(`#hmr-test3`)).toBe(null);
await expect(await getText(`#hmr-test4`)).toBe('bar');
expect(await getText(`#hmr-test3`)).toBe(null);
expect(await getText(`#hmr-test4`)).toBe('bar');
});

it('should apply changed styles', async () => {
11 changes: 10 additions & 1 deletion packages/e2e-tests/kit-node/jsconfig.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
}
12 changes: 9 additions & 3 deletions packages/e2e-tests/kit-node/package.json
Original file line number Diff line number Diff line change
@@ -5,15 +5,21 @@
"scripts": {
"dev": "svelte-kit dev",
"build": "svelte-kit build",
"preview": "svelte-kit preview"
"package": "svelte-kit package",
"preview": "svelte-kit preview",
"prepare": "svelte-kit sync",
"check": "svelte-check --tsconfig ./jsconfig.json",
"check:watch": "svelte-check --tsconfig ./jsconfig.json --watch"
},
"devDependencies": {
"@sveltejs/adapter-node": "^1.0.0-next.73",
"@sveltejs/kit": "^1.0.0-next.326",
"@sveltejs/kit": "^1.0.0-next.330",
"e2e-test-dep-svelte-api-only": "workspace:*",
"e2e-test-dep-vite-plugins": "workspace:*",
"svelte": "^3.48.0",
"svelte-i18n": "^3.4.0"
"svelte-check": "^2.2.6",
"svelte-i18n": "^3.4.0",
"typescript": "^4.6.4"
},
"type": "module",
"engines": {
10 changes: 10 additions & 0 deletions packages/e2e-tests/kit-node/src/app.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/// <reference types="@sveltejs/kit" />

// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare namespace App {
// interface Locals {}
// interface Platform {}
// interface Session {}
// interface Stuff {}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'fs';
import path from 'path';
import { getText, isBuild } from '../../testUtils';
import { getText, isBuild } from '~utils';

test('should render component imported via svelte field in package.json', async () => {
expect(await getText('#test-id')).toBe('svelte field works');
3 changes: 2 additions & 1 deletion packages/e2e-tests/package-json-svelte-field/package.json
Original file line number Diff line number Diff line change
@@ -15,5 +15,6 @@
"@sveltejs/vite-plugin-svelte": "workspace:*",
"svelte": "^3.48.0",
"vite": "^2.9.8"
}
},
"type": "module"
}
6 changes: 3 additions & 3 deletions packages/e2e-tests/package-json-svelte-field/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { svelte } = require('@sveltejs/vite-plugin-svelte');
const { defineConfig } = require('vite');
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';

module.exports = defineConfig(({ command, mode }) => {
export default defineConfig(({ command, mode }) => {
return {
plugins: [svelte()],
build: {
6 changes: 4 additions & 2 deletions packages/e2e-tests/package.json
Original file line number Diff line number Diff line change
@@ -4,6 +4,8 @@
"private": true,
"devDependencies": {
"css-color-names": "^1.0.1",
"tree-kill": "^1.2.2"
}
"tree-kill": "^1.2.2",
"vitest": "^0.12.6"
},
"type": "module"
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getColor, getText } from 'testUtils';
import { getColor, getText } from '~utils';

test('should render App', async () => {
expect(await getText('h1.foo')).toBe(`Hello world`);
3 changes: 2 additions & 1 deletion packages/e2e-tests/preprocess-with-vite/package.json
Original file line number Diff line number Diff line change
@@ -13,5 +13,6 @@
"stylus": "^0.57.0",
"svelte": "^3.48.0",
"vite": "^2.9.8"
}
},
"type": "commonjs"
}
Original file line number Diff line number Diff line change
@@ -6,8 +6,10 @@ import {
sleep,
getColor,
addFile,
removeFile
} from '../../testUtils';
removeFile,
page,
browserLogs
} from '~utils';

test('should render App', async () => {
expect(await getText('h1')).toBe(`I'm blue`);
3 changes: 2 additions & 1 deletion packages/e2e-tests/svelte-preprocess/package.json
Original file line number Diff line number Diff line change
@@ -13,5 +13,6 @@
"svelte-preprocess": "^4.10.6",
"typescript": "^4.6.4",
"vite": "^2.9.8"
}
},
"type": "module"
}
7 changes: 0 additions & 7 deletions packages/e2e-tests/svelte-preprocess/svelte.config.cjs

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const sveltePreprocess = require('svelte-preprocess');
import sveltePreprocess from 'svelte-preprocess';

module.exports = {
export default {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: sveltePreprocess()
6 changes: 3 additions & 3 deletions packages/e2e-tests/svelte-preprocess/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { defineConfig } = require('vite');
const { svelte } = require('@sveltejs/vite-plugin-svelte');
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';

module.exports = defineConfig(({ command, mode }) => {
export default defineConfig(({ command, mode }) => {
return {
plugins: [svelte()],
build: {
12 changes: 0 additions & 12 deletions packages/e2e-tests/testEnv.d.ts

This file was deleted.

49 changes: 31 additions & 18 deletions packages/e2e-tests/testUtils.ts
Original file line number Diff line number Diff line change
@@ -5,17 +5,13 @@ import fs from 'fs';
import path from 'path';
import colors from 'css-color-names';
import { ElementHandle } from 'playwright-core';
import fetch from 'node-fetch';

export const isBuild = !!process.env.VITE_TEST_BUILD;
export const isWin = process.platform === 'win32';
export const isCI = !!process.env.CI;
import { isBuild, isWin, isCI, page, testDir, viteTestUrl } from './vitestSetup';

export const hmrUpdateTimeout = 10000;
export * from './vitestSetup';

const testPath = expect.getState().testPath;
const segments = testPath.split(path.sep);
const testName = segments[segments.indexOf('e2e-tests') + 1];
export const testDir = path.resolve(__dirname, '../../temp', isBuild ? 'build' : 'serve', testName);
export const hmrUpdateTimeout = 10000;

const hexToNameMap: Record<string, string> = {};
Object.keys(colors).forEach((color) => {
@@ -96,13 +92,21 @@ export function findAssetFile(match: string | RegExp, base = '') {
/**
* Poll a getter until the value it returns includes the expected value.
*/
export async function untilUpdated(poll: () => string | Promise<string>, expected: string) {
export async function untilMatches(
getValue: () => string | Promise<string>,
matches: string,
msg: string
) {
if (isBuild) return;

const maxTries = process.env.CI ? 100 : 20;
for (let tries = 0; tries < maxTries; tries++) {
const actual = (await poll()) || '';
if (actual.indexOf(expected) > -1 || tries === maxTries - 1) {
expect(actual).toMatch(expected);
const current = await getValue();
if (current != null && typeof current !== 'string') {
throw new Error('getValue must return a string, received: ' + typeof current);
}
if (current?.includes(matches) || tries === maxTries - 1) {
expect(current, msg).toMatch(matches);
break;
} else {
await timeout(50);
@@ -149,7 +153,7 @@ export async function hmrUpdateComplete(file, timeout) {
}

export async function editFileAndWaitForHmrComplete(file, replacer, fileUpdateToWaitFor?) {
const newContent = await editFile(file, replacer);
const newContent = editFile(file, replacer);
if (!fileUpdateToWaitFor) {
fileUpdateToWaitFor = file;
}
@@ -161,7 +165,7 @@ export async function editFileAndWaitForHmrComplete(file, replacer, fileUpdateTo
for (let i = 1; i <= maxTries; i++) {
try {
console.log(`retry #${i} of hmr update for ${file}`);
await editFile(file, () => newContent + '\n'.repeat(i));
editFile(file, () => newContent + '\n'.repeat(i));
await hmrUpdateComplete(fileUpdateToWaitFor, hmrUpdateTimeout);
return;
} catch (e) {
@@ -173,13 +177,10 @@ export async function editFileAndWaitForHmrComplete(file, replacer, fileUpdateTo
}
}

export async function saveScreenshot(name?: string) {
export async function saveScreenshot(name: string) {
if (!page) {
return;
}
if (!name) {
name = expect.getState().currentTestName;
}
const filename = `${new Date().toISOString().replace(/\D/g, '')}_${name
.toLowerCase()
.replace(/[^a-z]/g, '_')}.jpeg`;
@@ -217,3 +218,15 @@ export async function waitForNavigation(opts: Parameters<typeof page.waitForNavi
clearTimeout(timeoutHandle);
});
}

export async function fetchPageText() {
// force ip v4 in dev as Vite also forces it.
// this will be fixed in Vite 3 when we can removed this trick.
const url = page.url().replace('localhost', isBuild ? 'localhost' : '127.0.0.1');
const res = await fetch(url);
if (res.ok) {
return res.text();
} else {
throw new Error(`request to ${url} failed with ${res.status} - ${res.statusText}.`);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isBuild, getText, editFileAndWaitForHmrComplete } from '../../testUtils';
import { isBuild, getText, editFileAndWaitForHmrComplete } from '~utils';

test('should render App', async () => {
expect(await getText('#hello')).toBe('Hello world');
3 changes: 2 additions & 1 deletion packages/e2e-tests/ts-type-import/package.json
Original file line number Diff line number Diff line change
@@ -14,5 +14,6 @@
"svelte": "^3.48.0",
"svelte-preprocess": "^4.10.6",
"vite": "^2.9.8"
}
},
"type": "module"
}
7 changes: 7 additions & 0 deletions packages/e2e-tests/ts-type-import/svelte.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import sveltePreprocess from 'svelte-preprocess';

export default {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: sveltePreprocess()
};
6 changes: 3 additions & 3 deletions packages/e2e-tests/ts-type-import/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { svelte } = require('@sveltejs/vite-plugin-svelte');
const { defineConfig } = require('vite');
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';

module.exports = defineConfig(() => {
export default defineConfig(() => {
return {
plugins: [svelte()],
build: {
31 changes: 19 additions & 12 deletions packages/e2e-tests/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
{
"include": ["."],
"exclude": ["**/dist/**"],
"compilerOptions": {
"target": "es2019",
"outDir": "dist",
"allowJs": true,
"esModuleInterop": true,
"moduleResolution": "node",
"baseUrl": ".",
"jsx": "preserve",
"types": ["vite/client", "jest", "node"]
}
"include": ["."],
"exclude": ["**/dist/**","**/build/**","**/node_modules/**"],
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"outDir": "dist",
"baseUrl": ".",
"allowJs": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"skipLibCheck": true,
"noUnusedLocals": true,
"jsx": "preserve",
"types": ["vite/client", "vitest/globals", "node"],
"paths": {
"~utils": ["./testUtils.ts"]
}
}
}
20 changes: 11 additions & 9 deletions packages/e2e-tests/vite-ssr-esm/__tests__/vite-ssr-esm.spec.ts
Original file line number Diff line number Diff line change
@@ -4,15 +4,17 @@ import {
getEl,
getText,
isBuild,
untilUpdated
} from '../../testUtils';

import fetch from 'node-fetch';
untilMatches,
page,
e2eServer,
browserLogs,
fetchPageText
} from '~utils';

test('/', async () => {
expect(await page.textContent('h1')).toMatch('Hello svelte world'); // after hydration

const html = await (await fetch(page.url())).text();
const html = await fetchPageText();
expect(html).toMatch('Hello world'); // before hydration
if (isBuild) {
// TODO expect preload links
@@ -25,7 +27,7 @@ test('css', async () => {
} else {
// During dev, the CSS is loaded from async chunk and we may have to wait
// when the test runs concurrently.
await untilUpdated(() => getColor('h1'), 'green');
await untilMatches(() => getColor('h1'), 'green', 'h1 has color green');
}
});

@@ -61,17 +63,17 @@ if (!isBuild) {
'<div id="hmr-test">foo</div>\n<!-- HMR-TEMPLATE-INJECT -->'
)
);
await expect(await getText(`#hmr-test`)).toBe('foo');
expect(await getText(`#hmr-test`)).toBe('foo');
});
test('should apply style update', async () => {
expect(await getColor(`h1`)).toBe('green');
await updateApp((content) => content.replace('color: green', 'color: red'));
expect(await getColor(`h1`)).toBe('red');
});
test('should not preserve state of updated props', async () => {
await expect(await getText(`#foo`)).toBe('foo');
expect(await getText(`#foo`)).toBe('foo');
await updateApp((content) => content.replace("foo = 'foo'", "foo = 'bar'"));
await expect(await getText(`#foo`)).toBe('bar');
expect(await getText(`#foo`)).toBe('bar');
});
});
}
20 changes: 11 additions & 9 deletions packages/e2e-tests/vite-ssr/__tests__/vite-ssr.spec.ts
Original file line number Diff line number Diff line change
@@ -4,15 +4,17 @@ import {
getEl,
getText,
isBuild,
untilUpdated
} from '../../testUtils';

import fetch from 'node-fetch';
untilMatches,
page,
e2eServer,
browserLogs,
fetchPageText
} from '~utils';

test('/', async () => {
expect(await page.textContent('h1')).toMatch('Hello svelte world'); // after hydration

const html = await (await fetch(page.url())).text();
const html = await fetchPageText();
expect(html).toMatch('Hello world'); // before hydration
if (isBuild) {
// TODO expect preload links
@@ -25,7 +27,7 @@ test('css', async () => {
} else {
// During dev, the CSS is loaded from async chunk and we may have to wait
// when the test runs concurrently.
await untilUpdated(() => getColor('h1'), 'green');
await untilMatches(() => getColor('h1'), 'green', 'h1 has color green');
}
});

@@ -57,17 +59,17 @@ if (!isBuild) {
'<div id="hmr-test">foo</div>\n<!-- HMR-TEMPLATE-INJECT -->'
)
);
await expect(await getText(`#hmr-test`)).toBe('foo');
expect(await getText(`#hmr-test`)).toBe('foo');
});
test('should apply style update', async () => {
expect(await getColor(`h1`)).toBe('green');
await updateApp((content) => content.replace('color: green', 'color: red'));
expect(await getColor(`h1`)).toBe('red');
});
test('should not preserve state of updated props', async () => {
await expect(await getText(`#foo`)).toBe('foo');
expect(await getText(`#foo`)).toBe('foo');
await updateApp((content) => content.replace("foo = 'foo'", "foo = 'bar'"));
await expect(await getText(`#foo`)).toBe('bar');
expect(await getText(`#foo`)).toBe('bar');
});
});
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
const os = require('os');
const fs = require('fs-extra');
const path = require('path');
const { chromium } = require('playwright-core');
const execa = require('execa');
import os from 'os';
import fs from 'fs-extra';
import path from 'path';
import { chromium } from 'playwright-core';
import { execa } from 'execa';
import { fileURLToPath } from 'url';

const isBuildTest = !!process.env.VITE_TEST_BUILD;
const tempTestDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'temp');

const isBuildTest = !!process.env.TEST_BUILD;
const isCI = !!process.env.CI;
const showTestBrowser = !!process.env.TEST_SHOW_BROWSER;
const preserveArtifacts = !!process.env.TEST_PRESERVE_ARTIFACTS || isCI;

const DIR = path.join(os.tmpdir(), 'jest_playwright_global_setup');
const DIR = path.join(os.tmpdir(), 'vitest_playwright_global_setup');

const buildPackagesUnderTest = async () => {
console.log('building packages');
@@ -43,7 +47,7 @@ const startPlaywrightServer = async () => {
});
};

module.exports = async () => {
export async function setup() {
if (!isCI) {
// TODO currently this builds twice when running yarn test
console.log('');
@@ -55,15 +59,28 @@ module.exports = async () => {
console.log('Starting playwright server ...');
const browserServer = await startPlaywrightServer();
console.log('Playwright server running');
global.__BROWSER_SERVER__ = browserServer;
console.log('storing wsEndpoint in ' + DIR);
await fs.mkdirp(DIR);
await fs.writeFile(path.join(DIR, 'wsEndpoint'), browserServer.wsEndpoint());
console.log('clearing previous test artifacts');
if (!process.env.VITE_PRESERVE_BUILD_ARTIFACTS) {
await fs.remove(path.resolve(__dirname, '..', 'temp'));
if (!preserveArtifacts) {
await fs.remove(tempTestDir);
} else {
await fs.remove(path.resolve(__dirname, '..', 'temp', isBuildTest ? 'build' : 'serve'));
await fs.remove(path.join(tempTestDir, isBuildTest ? 'build' : 'serve'));
}
console.log('jest global setup done');
};
console.log('vitest global setup done');
return async () => {
if (!preserveArtifacts) {
try {
await fs.remove(tempTestDir);
} catch (e) {
console.error('failed to clear ' + tempTestDir, e);
}
}
try {
await browserServer?.close();
} catch (e) {
console.error('failed to close browserServer', e);
}
};
}
192 changes: 107 additions & 85 deletions scripts/jestPerTestSetup.ts → packages/e2e-tests/vitestSetup.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,53 @@
import * as fs from 'fs-extra';
import * as path from 'path';
import { Page } from 'playwright-core';
import { chromium } from 'playwright-core';
import type { Browser, Page } from 'playwright-core';
import type { File } from 'vitest';
import { beforeAll } from 'vitest';
import os from 'os';
import { fileURLToPath } from 'url';

const isBuild = !!process.env.VITE_TEST_BUILD;
const isWin = process.platform === 'win32';
const isCI = !!process.env.CI;
export const isBuild = !!process.env.TEST_BUILD;
export const isWin = process.platform === 'win32';
export const isCI = !!process.env.CI;

function testDir() {
const testPath = expect.getState().testPath;
const segments = testPath.split(path.sep);
const testName = segments[segments.indexOf('e2e-tests') + 1];
return path.resolve(__dirname, '../temp', isBuild ? 'build' : 'serve', testName);
}
/**
* Path to the current test file
*/
export let testPath: string;
/**
* Path to the test folder
*/
export let testDir: string;
/**
* Test folder name
*/
export let testName: string;

// injected by the test env
declare global {
// eslint-disable-next-line no-unused-vars
namespace NodeJS {
// eslint-disable-next-line no-unused-vars
interface Global {
page?: Page;
viteTestUrl?: string;
e2eServer?: E2EServer;
}
}
export const serverLogs: string[] = [];
export const browserLogs: string[] = [];
export const browserErrors: Error[] = [];

export let page: Page = undefined!;
export let browser: Browser = undefined!;
export let viteTestUrl: string = '';
export let e2eServer: E2EServer;

export function setViteUrl(url: string) {
viteTestUrl = url;
}

export interface E2EServer {
port: number;
logs: { server?: { out: string[]; err: string[] }; build?: { out: string[]; err: string[] } };
close: () => {};
close: () => Promise<void>;
}

let server: E2EServer;
let tempDir: string;
let err: Error;

const logs = ((global as any).browserLogs = []);
const logs = browserLogs;
const onConsole = (msg) => {
logs.push(msg.text());
};
@@ -64,14 +75,25 @@ const getUniqueTestPort = async (testRoot, testName, isBuild) => {
return (isBuild ? 5500 : 3500) + idx;
};

const DIR = path.join(os.tmpdir(), 'vitest_playwright_global_setup');

beforeAll(
async () => {
const page = (global as any).page;
if (!page) {
async (s) => {
const suite = s as File;
if (!suite.filepath.includes('e2e-tests')) {
return;
}
const testPath = expect.getState().testPath;
const segments = testPath.split(path.sep);

const wsEndpoint = fs.readFileSync(path.join(DIR, 'wsEndpoint'), 'utf-8');
if (!wsEndpoint) {
throw new Error('wsEndpoint not found');
}

browser = await chromium.connect(wsEndpoint);
page = await browser.newPage();

const testPath = suite.filepath;
const segments = testPath.split('/');
const testName = segments.includes('e2e-tests')
? segments[segments.indexOf('e2e-tests') + 1]
: null;
@@ -80,10 +102,11 @@ beforeAll(
// start a vite server in that directory.
if (testName) {
page.on('console', onConsole);
const e2eTestsRoot = path.resolve(__dirname, '../packages/e2e-tests');
const e2eTestsRoot = path.dirname(fileURLToPath(import.meta.url));

const srcDir = path.resolve(e2eTestsRoot, testName);

tempDir = path.resolve(__dirname, '../temp', isBuild ? 'build' : 'serve', testName);
tempDir = path.resolve(e2eTestsRoot, '../../temp', isBuild ? 'build' : 'serve', testName);
const directoriesToIgnore = [
'node_modules',
'__tests__',
@@ -92,6 +115,7 @@ beforeAll(
'.svelte',
'.svelte-kit'
];
testDir = tempDir;
const isIgnored = (file) => {
const segments = file.split(path.sep);
return segments.some((segment) => directoriesToIgnore.includes(segment));
@@ -117,82 +141,80 @@ beforeAll(
const customServerScript = path.resolve(path.dirname(testPath), 'serve.js');
const defaultServerScript = path.resolve(e2eTestsRoot, 'e2e-server.js');
const hasCustomServer = fs.existsSync(customServerScript);
const { serve } = require(hasCustomServer ? customServerScript : defaultServerScript);
const serverScript = hasCustomServer ? customServerScript : defaultServerScript;
const { serve } = await import(serverScript);
const port = await getUniqueTestPort(e2eTestsRoot, testName, isBuild);
server = await serve(tempDir, isBuild, port);
(global as any).e2eServer = server;
const url = ((global as any).viteTestUrl = `http://localhost:${port}`);
e2eServer = server;
const url = (viteTestUrl = `http://localhost:${port}`);
await (isBuild ? page.goto(url) : goToUrlAndWaitForViteWSConnect(page, url));
}
} catch (e) {
// jest doesn't exit if our setup has error here
// https://github.com/facebook/jest/issues/2713
err = e;
console.error(`beforeAll failed for ${testName}.`, e);
// tests are still executed so close page to shorten
try {
await page.close();
} catch (e2) {
console.error('failed to close page on error', e2);
}
throw e;
}
},
isCI ? (isWin ? 60000 : 30000) : 15000
);

afterAll(async () => {
try {
const page = (global as any).page;
if (page) {
page.off('console', onConsole);
await page.close();
}
} catch (e) {
console.error('failed to close test page', e);
if (!err) {
err = e;
}
}
try {
await server?.close();
} catch (e) {
console.error('failed to close test server', e);
if (!err) {
err = e;
}
}
if (tempDir) {
// unlink node modules to prevent removal of linked modules on cleanup
const temp_node_modules = path.join(tempDir, 'node_modules');
try {
await fs.unlink(temp_node_modules);
} catch (e) {
console.error(`failed to unlink ${temp_node_modules}`);
if (!err) {
err = e;
return async () => {
try {
if (page) {
page.off('console', onConsole);
await page.close();
}
} catch (e) {
console.error('failed to close test page', e);
if (!err) {
err = e;
}
}
}
const logDir = path.join(testDir(), 'logs');
const logFile = path.join(logDir, 'browser.log');
try {
await fs.writeFile(logFile, logs.join('\n'));
} catch (e) {
console.error(`failed to write browserlogs in ${logFile}`, e);
if (!err) {
err = e;
try {
await e2eServer?.close();
} catch (e) {
console.error('failed to close test server', e);
if (!err) {
err = e;
}
}
if (tempDir) {
// unlink node modules to prevent removal of linked modules on cleanup
const temp_node_modules = path.join(tempDir, 'node_modules');
try {
await fs.unlink(temp_node_modules);
} catch (e) {
console.error(`failed to unlink ${temp_node_modules}`);
if (!err) {
err = e;
}
}
const logDir = path.join(tempDir, 'logs');
const logFile = path.join(logDir, 'browser.log');
try {
await fs.writeFile(logFile, logs.join('\n'));
} catch (e) {
console.error(`failed to write browserlogs in ${logFile}`, e);
if (!err) {
err = e;
}
}
}
}
}

if (err) {
throw err;
}
});
if (err) {
throw err;
}
};
},
isCI ? (isWin ? 60000 : 30000) : 20000
);

async function goToUrlAndWaitForViteWSConnect(page: Page, url: string) {
let timerId;
let pageConsoleListener;
const timeoutMS = 10000;
const timeoutMS = 15000;
const timeoutPromise = new Promise(
// eslint-disable-next-line no-unused-vars
(_, reject) =>
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { describe, it, expect } from 'vitest';
import { findRootSvelteDependencies, needsOptimization } from '../dependencies';
import * as path from 'path';
import { createRequire } from 'module';
import { fileURLToPath } from 'url';
const __dir = path.dirname(fileURLToPath(import.meta.url));
const e2eTestRoot = path.resolve(__dir, '../../../../../packages/e2e-tests');

describe('dependencies', () => {
describe('findRootSvelteDependencies', () => {
@@ -11,9 +15,7 @@ describe('dependencies', () => {
expect(deps[0].path).toEqual([]);
});
it('should find nested svelte dependencies in packages/e2e-test/package-json-svelte-field', () => {
const deps = findRootSvelteDependencies(
path.resolve('packages/e2e-tests/package-json-svelte-field')
);
const deps = findRootSvelteDependencies(path.join(e2eTestRoot, 'package-json-svelte-field'));
expect(deps).toHaveLength(3);
const hybrid = deps.find((dep) => dep.name === 'e2e-test-dep-svelte-hybrid');
expect(hybrid).toBeTruthy();
@@ -29,7 +31,8 @@ describe('dependencies', () => {
});
describe('needsOptimization', () => {
it('should optimize cjs deps only', () => {
const localRequire = createRequire(path.resolve('packages/e2e-tests/dependencies'));
const testDepsPath = path.join(e2eTestRoot, 'dependencies/package.json');
const localRequire = createRequire(testDepsPath);
expect(needsOptimization('e2e-test-dep-cjs-and-esm', localRequire)).toBe(false);
expect(needsOptimization('e2e-test-dep-cjs-only', localRequire)).toBe(true);
expect(needsOptimization('e2e-test-dep-esm-only', localRequire)).toBe(false);
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { describe, it, expect } from 'vitest';
import { buildMagicString, buildSourceMap } from '../sourcemap';

describe('sourcemap', () => {
3,204 changes: 604 additions & 2,600 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

43 changes: 0 additions & 43 deletions scripts/jestEnv.js

This file was deleted.

9 changes: 0 additions & 9 deletions scripts/jestGlobalTeardown.js

This file was deleted.

39 changes: 39 additions & 0 deletions vitest.config.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as path from 'path';
import * as os from 'os';
// eslint-disable-next-line node/no-missing-import
import { defineConfig } from 'vitest/config';
import { fileURLToPath } from 'url';

const timeout = process.env.CI ? 50000 : 30000;
const __dir = path.dirname(fileURLToPath(import.meta.url));
const utilsPath = path.resolve(__dir, 'packages/e2e-tests/testUtils');

// too many threads cause vite-ssr tests to fail randomly, limit to at most 33%
const fractionOfAvailableThreads = (f: number) =>
Math.max(1, Math.floor((os.cpus()?.length || 1) * f));
const numThreads = fractionOfAvailableThreads(1 / 3);

export default defineConfig({
resolve: {
alias: {
'~utils': utilsPath
}
},
test: {
include: ['./packages/e2e-tests/**/*.spec.[tj]s'],
setupFiles: ['./packages/e2e-tests/vitestSetup.ts'],
globalSetup: ['./packages/e2e-tests/vitestGlobalSetup.ts'],
testTimeout: timeout,
hookTimeout: timeout,
globals: true,
reporters: 'dot',
onConsoleLog(log) {
if (log.match(/experimental|jit engine|emitted file/i)) return false;
},
minThreads: numThreads,
maxThreads: numThreads
},
esbuild: {
target: 'node14'
}
});
15 changes: 15 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// eslint-disable-next-line node/no-missing-import
import { defineConfig } from 'vitest/config';

export default defineConfig({
test: {
exclude: ['**/node_modules/**', '**/dist/**', './packages/e2e-tests/**/*.*', './temp/**/*.*'],
testTimeout: 20000,
reporters: 'dot',
maxThreads: process.env.CI ? 1 : undefined,
minThreads: process.env.CI ? 1 : undefined
},
esbuild: {
target: 'node14'
}
});

0 comments on commit 5b036e8

Please sign in to comment.