update puppeteer jest setup

This commit is contained in:
Rene
2020-09-05 19:45:20 +02:00
parent e11e36531f
commit 38d26495c4
15 changed files with 2532 additions and 153 deletions
+3
View File
@@ -69,6 +69,7 @@ module.exports = {
'no-void': 'off',
'no-empty-function': 'off',
'no-new-func': 'off',
'import/no-unresolved': ['error', { ignore: ['./build/build.html$'] }],
},
globals: {
page: true,
@@ -81,6 +82,8 @@ module.exports = {
files: ['rollup.config.*'],
rules: {
'no-console': 'off',
'global-require': 'off',
'import/no-dynamic-require': 'off',
},
},
],
+12
View File
@@ -8,6 +8,18 @@
"endOfLine": "lf",
"parser": "babel-ts",
"overrides": [
{
"files": "*.html",
"options": { "parser": "html" }
},
{
"files": "*.css",
"options": { "parser": "css" }
},
{
"files": "*.scss",
"options": { "parser": "scss" }
},
{
"files": "*.vue",
"options": { "parser": "vue" }
+2 -90
View File
@@ -1,99 +1,11 @@
const path = require('path');
const del = require('del');
const rollup = require('rollup');
const babel = require('@babel/core');
const PuppeteerEnvironment = require('jest-environment-puppeteer');
const resolve = require('./resolve.config.json');
const rollupInputFile = 'index';
const rollupOutputFile = 'index';
const rollupOutputDir = 'build';
const rollupNodeEnv = 'build';
const getRollupInfos = (testPath) => {
const projectRootPath = path.resolve(__dirname, resolve.projectRoot);
const testDir = path.dirname(testPath);
const input = path.resolve(testDir, rollupInputFile);
const dist = path.resolve(testDir, rollupOutputDir);
const file = rollupOutputFile;
return {
projectRootPath,
input,
dist,
file,
};
};
const rollupTest = async (testPath) => {
const { projectRootPath, input, dist, file } = getRollupInfos(testPath);
const testPathSplit = path.relative(projectRootPath, testPath).split(path.sep);
if (testPathSplit.length > 0) {
const env = process.env.NODE_ENV;
const project = testPathSplit[0];
const { code: rollupConfigCode } = await babel.transformFileSync('./rollup.config.js', {});
process.env.NODE_ENV = rollupNodeEnv;
// eslint-disable-next-line no-eval
let rollupConfig = await eval(rollupConfigCode)(
{ 'config-project': project },
{
input,
dist,
file,
types: null,
minVersions: false,
esmBuild: false,
sourcemap: false,
},
true
);
if (!Array.isArray(rollupConfig)) {
rollupConfig = [rollupConfig];
}
for (let i = 0; i < rollupConfig.length; i++) {
const inputConfig = rollupConfig[i];
let { output } = inputConfig;
// eslint-disable-next-line no-await-in-loop
const bundle = await rollup.rollup(inputConfig);
if (!Array.isArray(output)) {
output = [output];
}
for (let v = 0; v < output.length; v++) {
const outputConfig = output[i];
// eslint-disable-next-line no-await-in-loop
await bundle.write(outputConfig);
}
}
process.env.NODE_ENV = env;
}
};
const cleanRollupTest = async (testPath) => {
const { dist } = getRollupInfos(testPath);
await del(dist);
};
class CustomEnvironment extends PuppeteerEnvironment {
constructor(config, context) {
super(config, context);
this.ctx = context;
}
const PuppeteerRollupEnvironment = require('./jest-puppeteer.env.rollup.js');
class CustomEnvironment extends PuppeteerRollupEnvironment {
async setup() {
await rollupTest(this.ctx.testPath);
await super.setup();
}
async teardown() {
await cleanRollupTest(this.ctx.testPath);
await super.teardown();
}
}
+162
View File
@@ -0,0 +1,162 @@
const PuppeteerEnvironment = require('jest-environment-puppeteer');
const fs = require('fs');
const path = require('path');
const del = require('del');
const rollup = require('rollup');
const rollupPluginHtml = require('@rollup/plugin-html');
const rollupPluginStyles = require('rollup-plugin-styles');
const rollupConfig = require('./rollup.config.js');
const resolve = require('./resolve.config.json');
const rollupInputHtmlFile = 'index.html';
const rollupInputFile = 'index';
const rollupOutputHtmlFile = 'build.html';
const rollupOutputFile = 'build';
const rollupOutputDir = 'build';
const rollupNodeEnv = 'build';
const getRollupInfos = (testPath) => {
const projectRootPath = path.resolve(__dirname, resolve.projectRoot);
const testDir = path.dirname(testPath);
const input = path.resolve(testDir, rollupInputFile);
const dist = path.resolve(testDir, rollupOutputDir);
const file = rollupOutputFile;
const testName = path.basename(testDir);
return {
projectRootPath,
testDir,
testName,
input,
dist,
file,
};
};
const makeHtmlAttributes = (attributes) => {
if (!attributes) {
return '';
}
const keys = Object.keys(attributes);
// eslint-disable-next-line no-param-reassign
// eslint-disable-next-line no-return-assign
return keys.reduce((result, key) => (result += ` ${key}="${attributes[key]}"`), '');
};
const genHtmlTemplateFunc = (content) => ({ attributes, files, meta, publicPath, title }) => {
const scripts = (files.js || [])
.map(({ fileName }) => `<script src="${publicPath}${fileName}"${makeHtmlAttributes(attributes.script)}></script>`)
.join('\n');
const links = (files.css || [])
.map(({ fileName }) => `<link href="${publicPath}${fileName}" rel="stylesheet"${makeHtmlAttributes(attributes.link)}>`)
.join('\n');
const metas = meta.map((input) => `<meta${makeHtmlAttributes(input)}>`).join('\n');
return `<!doctype html>
<html${makeHtmlAttributes(attributes.html)}>
<head>
${metas}
<title>${title}</title>
${links}
</head>
<body>
${content || ''}
${scripts}
</body>
</html>`;
};
const setupRollupTest = async (testPath) => {
const { projectRootPath, input, dist, file, testName, testDir } = getRollupInfos(testPath);
const testPathSplit = path.relative(projectRootPath, testPath).split(path.sep);
if (testPathSplit.length > 0) {
const [project] = testPathSplit;
const env = process.env.NODE_ENV;
try {
process.env.NODE_ENV = rollupNodeEnv;
const htmlFilePath = path.resolve(testDir, rollupInputHtmlFile);
const htmlFileContent = fs.existsSync(htmlFilePath) ? fs.readFileSync(htmlFilePath, 'utf8') : null;
let rollupConfigObj = rollupConfig(
{ 'config-project': project },
{
overwrite: {
input,
dist,
file,
types: null,
minVersions: false,
esmBuild: false,
sourcemap: false,
pipeline: [
rollupPluginStyles(),
...rollupConfig.defaults.pipeline,
rollupPluginHtml({
title: `Jest-Puppeteer: ${testName}`,
fileName: rollupOutputHtmlFile,
template: genHtmlTemplateFunc(htmlFileContent),
meta: [{ charset: 'utf-8' }, { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge' }],
}),
],
},
silent: true,
fast: true,
check: false,
}
);
if (!Array.isArray(rollupConfigObj)) {
rollupConfigObj = [rollupConfigObj];
}
for (let i = 0; i < rollupConfigObj.length; i++) {
const inputConfig = rollupConfigObj[i];
let { output } = inputConfig;
// eslint-disable-next-line no-await-in-loop
const bundle = await rollup.rollup(inputConfig);
if (!Array.isArray(output)) {
output = [output];
}
for (let v = 0; v < output.length; v++) {
const outputConfig = output[i];
// eslint-disable-next-line no-await-in-loop
await bundle.write(outputConfig);
}
}
} catch (e) {
console.warn(e);
}
process.env.NODE_ENV = env;
}
};
const cleanupRollupTest = (testPath) => {
const { dist } = getRollupInfos(testPath);
del(dist);
};
class PuppeteerRollupEnvironment extends PuppeteerEnvironment {
constructor(config, context) {
super(config, context);
this.ctx = context;
}
async setup() {
await setupRollupTest(this.ctx.testPath);
await super.setup();
}
async teardown() {
cleanupRollupTest(this.ctx.testPath);
await super.teardown();
}
}
module.exports = PuppeteerRollupEnvironment;
+5
View File
@@ -24,8 +24,13 @@ module.exports = {
...base,
preset: 'jest-puppeteer',
displayName: 'puppeteer',
setupFilesAfterEnv: ['expect-puppeteer'],
testMatch: ['**/__tests__/puppeteer/**/*.test.[jt]s?(x)'],
testEnvironment: './jest-puppeteer.env.js',
transform: {
'^.+\\.[jt]sx?$': 'babel-jest',
'^.+\\.html?$': 'html-loader-jest',
},
},
],
};
+2230
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -10,8 +10,10 @@
"@babel/preset-typescript": "^7.10.4",
"@rollup/plugin-babel": "^5.1.0",
"@rollup/plugin-commonjs": "^14.0.0",
"@rollup/plugin-html": "^0.2.0",
"@rollup/plugin-node-resolve": "^8.4.0",
"@rollup/plugin-typescript": "^5.0.2",
"@types/expect-puppeteer": "^4.4.3",
"@types/jest": "^25.2.3",
"@types/jest-environment-puppeteer": "^4.3.2",
"@types/puppeteer": "^3.0.1",
@@ -32,14 +34,18 @@
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react": "^7.20.3",
"eslint-plugin-react-hooks": "^4.0.8",
"expect-puppeteer": "^4.4.0",
"html-loader-jest": "^0.2.1",
"jest": "^26.0.1",
"jest-puppeteer": "^4.4.0",
"mkdirp": "^1.0.4",
"node-sass": "^4.14.1",
"prettier": "^2.0.5",
"prettier-eslint": "^11.0.0",
"puppeteer": "^5.2.1",
"rollup": "^2.22.1",
"rollup-plugin-prettier": "^2.1.0",
"rollup-plugin-styles": "^3.10.0",
"rollup-plugin-terser": "^6.1.0",
"rollup-plugin-typescript2": "^0.27.1",
"tslib": "^2.0.0",
@@ -0,0 +1,4 @@
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>
@@ -1,9 +1,15 @@
describe('Google', () => {
import html from './build/build.html';
describe('Environment', () => {
beforeAll(async () => {
await page.goto('https://google.com');
await page.setContent(html, { waitUntil: 'domcontentloaded' });
});
it('should be titled "Google"', async () => {
await expect(page.title()).resolves.toMatch('Google');
it('should be titled "Environment"', async () => {
await expect(page).toMatchElement('#a');
await expect(page).toMatchElement('#b');
await expect(page).toMatchElement('#c');
await expect(page).toMatchElement('#d');
await expect(page.title()).resolves.toMatch('Environment');
});
});
@@ -1,4 +1,6 @@
import { Environment } from 'environment';
import 'some.scss';
import 'some.css';
// eslint-disable-next-line
console.log(new Environment());
+14
View File
@@ -0,0 +1,14 @@
declare module '*.css' {
const content: string;
export default content;
}
declare module '*.scss' {
const content: string;
export default content;
}
declare module '*.html' {
const content: string;
export default content;
}
+3
View File
@@ -0,0 +1,3 @@
body {
background: blue;
}
+5
View File
@@ -0,0 +1,5 @@
$c: red;
body {
background: $c;
}
+1 -1
View File
@@ -1,5 +1,5 @@
{
"extensions": [".json", ".js", "jsx", ".ts", ".tsx", ".html"],
"extensions": [".json", ".js", "jsx", ".mjs", ".ts", ".tsx"],
"directories": ["node_modules", "src"],
"projectRoot": "./packages"
}
+73 -58
View File
@@ -1,13 +1,13 @@
import rollupCommonjs from '@rollup/plugin-commonjs';
import rollupResolve from '@rollup/plugin-node-resolve';
import rollupTypescript from 'rollup-plugin-typescript2';
import rollupPrettier from 'rollup-plugin-prettier';
import rollupBabelPlugin from '@rollup/plugin-babel';
import { terser as rollupTerser } from 'rollup-plugin-terser';
import del from 'del';
import fs from 'fs';
import path from 'path';
import resolve from './resolve.config.json';
const { nodeResolve: rollupResolve } = require('@rollup/plugin-node-resolve');
const { babel: rollupBabelPlugin } = require('@rollup/plugin-babel');
const { terser: rollupTerser } = require('rollup-plugin-terser');
const rollupCommonjs = require('@rollup/plugin-commonjs');
const rollupTypescript = require('rollup-plugin-typescript2');
const rollupPrettier = require('rollup-plugin-prettier');
const del = require('del');
const fs = require('fs');
const path = require('path');
const resolve = require('./resolve.config.json');
const buildConfigNames = ['build.config.js', 'build.config.json'];
const buildConfigDefaults = {
@@ -21,6 +21,7 @@ const buildConfigDefaults = {
sourcemap: true,
esmBuild: true,
exports: 'auto',
pipeline: ['resolve', 'commonjs', 'typescript', 'babel'],
};
const legacyBabelConfig = {
@@ -69,23 +70,24 @@ const resolvePath = (projectPath, rPath, appendExt) => {
return result && appendExt ? appendExtension(result) : result;
};
export default async (config, overwriteBuildConfig, silent) => {
const rollupConfig = (config, { overwrite: overwriteBuildConfig, silent, fast, check = true } = {}) => {
const { 'config-project': project } = config;
const projectPath = path.resolve(__dirname, resolve.projectRoot, project);
const packageJSONPath = path.resolve(projectPath, 'package.json');
const tsconfigJSONPath = path.resolve(projectPath, 'tsconfig.json');
const buildConfigPath = getBuildConfig(projectPath);
const isTypeScriptProject = fs.existsSync(tsconfigJSONPath);
const buildConfig = {
...buildConfigDefaults,
...{ name: project, file: project },
...(await import(buildConfigPath)),
...require(buildConfigPath),
...(overwriteBuildConfig || {}),
};
const { input, src, dist, types, tests, file, cache, minVersions, sourcemap, esmBuild, name, exports, globals } = buildConfig;
const { devDependencies = {}, peerDependencies = {} } = await import(packageJSONPath);
const { input, src, dist, types, tests, file, cache, minVersions, sourcemap, esmBuild, name, exports, globals, pipeline } = buildConfig;
const { devDependencies = {}, peerDependencies = {} } = require(packageJSONPath);
const srcPath = resolvePath(projectPath, src);
const distPath = resolvePath(projectPath, dist);
@@ -97,21 +99,55 @@ export default async (config, overwriteBuildConfig, silent) => {
format: esm ? 'esm' : 'umd',
file: path.resolve(distPath, `${file}${esm ? '.esm' : ''}.js`),
sourcemap,
...(esm
? {}
: {
name,
globals,
exports,
}),
...(!esm && {
name,
globals,
exports,
}),
plugins: [
rollupPrettier({
sourcemap: sourcemap && 'silent',
}),
...(fast
? []
: [
rollupPrettier({
sourcemap: sourcemap && 'silent',
}),
]),
],
});
const genConfig = async ({ esm, typeDeclaration }) => {
const genConfig = ({ esm, typeDeclaration }) => {
const pipelineMap = {
resolve: rollupResolve({
extensions: resolve.extensions,
rootDir: srcPath,
customResolveOptions: {
moduleDirectory: [...resolve.directories.map((dir) => path.resolve(projectPath, dir)), path.resolve(__dirname, 'node_modules')],
},
}),
commonjs: rollupCommonjs(),
typescript: isTypeScriptProject
? rollupTypescript({
check,
useTsconfigDeclarationDir: true,
tsconfig: tsconfigJSONPath,
tsconfigOverride: {
compilerOptions: {
target: 'ESNext',
sourceMap: sourcemap,
declaration: typeDeclaration && types !== null,
declarationDir: typesPath,
},
exclude: (require(tsconfigJSONPath).exclude || []).concat(testsPath),
},
})
: {},
babel: rollupBabelPlugin({
...(esm ? esmBabelConfig : legacyBabelConfig),
babelHelpers: 'runtime',
extensions: resolve.extensions,
}),
};
const output = genOutputConfig(esm);
return {
input: inputPath,
@@ -133,37 +169,12 @@ export default async (config, overwriteBuildConfig, silent) => {
: []
),
external: [...Object.keys(devDependencies), ...Object.keys(peerDependencies)],
plugins: [
rollupResolve({
extensions: resolve.extensions,
rootDir: srcPath,
customResolveOptions: {
moduleDirectory: [...resolve.directories.map((dir) => path.resolve(projectPath, dir)), path.resolve(__dirname, 'node_modules')],
},
}),
rollupCommonjs(),
isTypeScriptProject
? rollupTypescript({
check: true,
useTsconfigDeclarationDir: true,
tsconfig: tsconfigJSONPath,
tsconfigOverride: {
compilerOptions: {
target: 'ESNext',
sourceMap: true,
declaration: typeDeclaration && types !== null,
declarationDir: typesPath,
},
exclude: ((await import(tsconfigJSONPath)).exclude || []).concat(testsPath),
},
})
: {},
rollupBabelPlugin({
...(esm ? esmBabelConfig : legacyBabelConfig),
babelHelpers: 'runtime',
extensions: resolve.extensions,
}),
],
plugins: pipeline.map((item) => {
if (typeof item === 'string') {
return pipelineMap[item];
}
return item;
}),
};
};
@@ -174,8 +185,8 @@ export default async (config, overwriteBuildConfig, silent) => {
console.log('CONFIG : ', buildConfig);
}
const legacy = await genConfig({ esm: false, typeDeclaration: true });
const esm = esmBuild ? await genConfig({ esm: true, typeDeclaration: false }) : null;
const legacy = genConfig({ esm: false, typeDeclaration: true });
const esm = esmBuild ? genConfig({ esm: true, typeDeclaration: false }) : null;
const builds = [legacy, esm]
.filter((build) => build !== null)
@@ -212,3 +223,7 @@ export default async (config, overwriteBuildConfig, silent) => {
return builds;
};
rollupConfig.defaults = buildConfigDefaults;
module.exports = rollupConfig;