prettierfy test files

pull/618/head
Rich Harris 7 years ago
parent 66e4c7307a
commit 10ecd81734

@ -1,9 +1,9 @@
import deindent from '../../src/utils/deindent.js';
import assert from 'assert';
import { svelte } from '../helpers.js';
import deindent from "../../src/utils/deindent.js";
import assert from "assert";
import { svelte } from "../helpers.js";
describe( 'create', () => {
it( 'should return a component constructor', () => {
describe("create", () => {
it("should return a component constructor", () => {
const source = deindent`
<div>{{prop}}</div>
`;
@ -12,7 +12,7 @@ describe( 'create', () => {
assert(component instanceof Function);
});
it( 'should throw error when source is invalid ', done => {
it("should throw error when source is invalid ", done => {
const source = deindent`
<div>{{prop}</div>
`;
@ -26,7 +26,7 @@ describe( 'create', () => {
assert.equal(component, undefined);
});
it( 'should return undefined when source is invalid ', () => {
it("should return undefined when source is invalid ", () => {
const source = deindent`
<div>{{prop}</div>
`;

@ -1,34 +1,39 @@
import assert from 'assert';
import * as fs from 'fs';
import { svelte } from '../helpers.js';
import assert from "assert";
import * as fs from "fs";
import { svelte } from "../helpers.js";
function tryRequire(file) {
try {
return require(file).default;
} catch (err) {
if ( err.code !== 'MODULE_NOT_FOUND' ) throw err;
if (err.code !== "MODULE_NOT_FOUND") throw err;
return null;
}
}
describe( 'css', () => {
fs.readdirSync( 'test/css/samples' ).forEach( dir => {
if ( dir[0] === '.' ) return;
describe("css", () => {
fs.readdirSync("test/css/samples").forEach(dir => {
if (dir[0] === ".") return;
// add .solo to a sample directory name to only run that test
const solo = /\.solo/.test(dir);
if (solo && process.env.CI) {
throw new Error( 'Forgot to remove `solo: true` from test' );
throw new Error("Forgot to remove `solo: true` from test");
}
(solo ? it.only : it)(dir, () => {
const config = tryRequire(`./samples/${dir}/_config.js`) || {};
const input = fs.readFileSync( `test/css/samples/${dir}/input.html`, 'utf-8' ).replace( /\s+$/, '' );
const input = fs
.readFileSync(`test/css/samples/${dir}/input.html`, "utf-8")
.replace(/\s+$/, "");
const actual = svelte.compile(input, config).css;
fs.writeFileSync(`test/css/samples/${dir}/_actual.css`, actual);
const expected = fs.readFileSync( `test/css/samples/${dir}/expected.css`, 'utf-8' );
const expected = fs.readFileSync(
`test/css/samples/${dir}/expected.css`,
"utf-8"
);
assert.equal(actual.trim(), expected.trim());
});

@ -1,18 +1,20 @@
import deindent from '../../src/utils/deindent.js';
import assert from 'assert';
import { svelte, env, setupHtmlEqual } from '../helpers.js';
import deindent from "../../src/utils/deindent.js";
import assert from "assert";
import { svelte, env, setupHtmlEqual } from "../helpers.js";
function testAmd(code, expectedId, dependencies, html) {
const fn = new Function( 'define', code );
const fn = new Function("define", code);
return env().then(window => {
function define(id, deps, factory) {
assert.equal(id, expectedId);
assert.deepEqual(deps, Object.keys(dependencies));
const SvelteComponent = factory( ...Object.keys( dependencies ).map( key => dependencies[ key ] ) );
const SvelteComponent = factory(
...Object.keys(dependencies).map(key => dependencies[key])
);
const main = window.document.body.querySelector( 'main' );
const main = window.document.body.querySelector("main");
const component = new SvelteComponent({ target: main });
assert.htmlEqual(main.innerHTML, html);
@ -27,7 +29,7 @@ function testAmd ( code, expectedId, dependencies, html ) {
}
function testCjs(code, dependencyById, html) {
const fn = new Function( 'module', 'exports', 'require', code );
const fn = new Function("module", "exports", "require", code);
return env().then(window => {
const module = { exports: {} };
@ -39,7 +41,7 @@ function testCjs ( code, dependencyById, html ) {
const SvelteComponent = module.exports;
const main = window.document.body.querySelector( 'main' );
const main = window.document.body.querySelector("main");
const component = new SvelteComponent({ target: main });
assert.htmlEqual(main.innerHTML, html);
@ -52,9 +54,11 @@ function testIife ( code, name, globals, html ) {
const fn = new Function(Object.keys(globals), `${code}\n\nreturn ${name};`);
return env().then(window => {
const SvelteComponent = fn( ...Object.keys( globals ).map( key => globals[ key ] ) );
const SvelteComponent = fn(
...Object.keys(globals).map(key => globals[key])
);
const main = window.document.body.querySelector( 'main' );
const main = window.document.body.querySelector("main");
const component = new SvelteComponent({ target: main });
assert.htmlEqual(main.innerHTML, html);
@ -67,9 +71,11 @@ function testEval ( code, name, globals, html ) {
const fn = new Function(Object.keys(globals), `return ${code};`);
return env().then(window => {
const SvelteComponent = fn( ...Object.keys( globals ).map( key => globals[ key ] ) );
const SvelteComponent = fn(
...Object.keys(globals).map(key => globals[key])
);
const main = window.document.body.querySelector( 'main' );
const main = window.document.body.querySelector("main");
const component = new SvelteComponent({ target: main });
assert.htmlEqual(main.innerHTML, html);
@ -78,11 +84,11 @@ function testEval ( code, name, globals, html ) {
});
}
describe( 'formats', () => {
describe("formats", () => {
before(setupHtmlEqual);
describe( 'amd', () => {
it( 'generates an AMD module', () => {
describe("amd", () => {
it("generates an AMD module", () => {
const source = deindent`
<div>{{answer}}</div>
@ -98,16 +104,16 @@ describe( 'formats', () => {
`;
const { code } = svelte.compile(source, {
format: 'amd',
amd: { id: 'foo' }
format: "amd",
amd: { id: "foo" }
});
return testAmd( code, 'foo', { answer: 42 }, `<div>42</div>` );
return testAmd(code, "foo", { answer: 42 }, `<div>42</div>`);
});
});
describe( 'cjs', () => {
it( 'generates a CommonJS module', () => {
describe("cjs", () => {
it("generates a CommonJS module", () => {
const source = deindent`
<div>{{answer}}</div>
@ -123,15 +129,15 @@ describe( 'formats', () => {
`;
const { code } = svelte.compile(source, {
format: 'cjs'
format: "cjs"
});
return testCjs(code, { answer: 42 }, `<div>42</div>`);
});
});
describe( 'iife', () => {
it( 'generates a self-executing script', () => {
describe("iife", () => {
it("generates a self-executing script", () => {
const source = deindent`
<div>{{answer}}</div>
@ -147,19 +153,19 @@ describe( 'formats', () => {
`;
const { code } = svelte.compile(source, {
format: 'iife',
name: 'Foo',
format: "iife",
name: "Foo",
globals: {
answer: 'answer'
answer: "answer"
}
});
return testIife( code, 'Foo', { answer: 42 }, `<div>42</div>` );
return testIife(code, "Foo", { answer: 42 }, `<div>42</div>`);
});
});
describe( 'umd', () => {
it( 'generates a UMD build', () => {
describe("umd", () => {
it("generates a UMD build", () => {
const source = deindent`
<div>{{answer}}</div>
@ -175,24 +181,24 @@ describe( 'formats', () => {
`;
const { code } = svelte.compile(source, {
format: 'umd',
name: 'Foo',
format: "umd",
name: "Foo",
globals: {
answer: 'answer'
answer: "answer"
},
amd: {
id: 'foo'
id: "foo"
}
});
return testAmd( code, 'foo', { answer: 42 }, `<div>42</div>` )
return testAmd(code, "foo", { answer: 42 }, `<div>42</div>`)
.then(() => testCjs(code, { answer: 42 }, `<div>42</div>`))
.then( () => testIife( code, 'Foo', { answer: 42 }, `<div>42</div>` ) );
.then(() => testIife(code, "Foo", { answer: 42 }, `<div>42</div>`));
});
});
describe( 'eval', () => {
it( 'generates a self-executing script that returns the component on eval', () => {
describe("eval", () => {
it("generates a self-executing script that returns the component on eval", () => {
const source = deindent`
<div>{{answer}}</div>
@ -208,13 +214,13 @@ describe( 'formats', () => {
`;
const { code } = svelte.compile(source, {
format: 'eval',
format: "eval",
globals: {
answer: 'answer'
answer: "answer"
}
});
return testEval( code, 'Foo', { answer: 42 }, `<div>42</div>` );
return testEval(code, "Foo", { answer: 42 }, `<div>42</div>`);
});
});
});

@ -1,11 +1,11 @@
import jsdom from 'jsdom';
import assert from 'assert';
import * as fs from 'fs';
import jsdom from "jsdom";
import assert from "assert";
import * as fs from "fs";
import * as consoleGroup from 'console-group';
import * as consoleGroup from "console-group";
consoleGroup.install();
import * as sourceMapSupport from 'source-map-support';
import * as sourceMapSupport from "source-map-support";
sourceMapSupport.install();
// for coverage purposes, we need to test source files,
@ -13,9 +13,9 @@ sourceMapSupport.install();
export function loadSvelte(test) {
if (test) global.__svelte_test = true;
const resolved = process.env.COVERAGE ?
require.resolve( '../src/index.js' ) :
require.resolve( '../compiler/svelte.js' );
const resolved = process.env.COVERAGE
? require.resolve("../src/index.js")
: require.resolve("../compiler/svelte.js");
delete require.cache[resolved];
return require(resolved);
@ -36,23 +36,23 @@ export function tryToLoadJson ( file ) {
try {
return JSON.parse(fs.readFileSync(file));
} catch (err) {
if ( err.code !== 'ENOENT' ) throw err;
if (err.code !== "ENOENT") throw err;
return null;
}
}
export function tryToReadFile(file) {
try {
return fs.readFileSync( file, 'utf-8' );
return fs.readFileSync(file, "utf-8");
} catch (err) {
if ( err.code !== 'ENOENT' ) throw err;
if (err.code !== "ENOENT") throw err;
return null;
}
}
export function env() {
return new Promise((fulfil, reject) => {
jsdom.env( '<main></main>', ( err, window ) => {
jsdom.env("<main></main>", (err, window) => {
if (err) {
reject(err);
} else {
@ -74,23 +74,25 @@ function cleanChildren ( node ) {
}
if (child.nodeType === 3) {
if ( node.namespaceURI === 'http://www.w3.org/2000/svg' && node.tagName !== 'text' && node.tagName !== 'tspan' ) {
if (
node.namespaceURI === "http://www.w3.org/2000/svg" &&
node.tagName !== "text" &&
node.tagName !== "tspan"
) {
node.removeChild(child);
}
child.data = child.data.replace( /\s{2,}/, '\n' );
child.data = child.data.replace(/\s{2,}/, "\n");
// text
if (previous && previous.nodeType === 3) {
previous.data += child.data;
previous.data = previous.data.replace( /\s{2,}/, '\n' );
previous.data = previous.data.replace(/\s{2,}/, "\n");
node.removeChild(child);
child = previous;
}
}
else {
} else {
cleanChildren(child);
}
@ -99,12 +101,12 @@ function cleanChildren ( node ) {
// collapse whitespace
if (node.firstChild && node.firstChild.nodeType === 3) {
node.firstChild.data = node.firstChild.data.replace( /^\s+/, '' );
node.firstChild.data = node.firstChild.data.replace(/^\s+/, "");
if (!node.firstChild.data) node.removeChild(node.firstChild);
}
if (node.lastChild && node.lastChild.nodeType === 3) {
node.lastChild.data = node.lastChild.data.replace( /\s+$/, '' );
node.lastChild.data = node.lastChild.data.replace(/\s+$/, "");
if (!node.lastChild.data) node.removeChild(node.lastChild);
}
}
@ -112,12 +114,16 @@ function cleanChildren ( node ) {
export function setupHtmlEqual() {
return env().then(window => {
assert.htmlEqual = (actual, expected, message) => {
window.document.body.innerHTML = actual.replace( />[\s\r\n]+</g, '><' ).trim();
cleanChildren( window.document.body, '' );
window.document.body.innerHTML = actual
.replace(/>[\s\r\n]+</g, "><")
.trim();
cleanChildren(window.document.body, "");
actual = window.document.body.innerHTML;
window.document.body.innerHTML = expected.replace( />[\s\r\n]+</g, '><' ).trim();
cleanChildren( window.document.body, '' );
window.document.body.innerHTML = expected
.replace(/>[\s\r\n]+</g, "><")
.trim();
cleanChildren(window.document.body, "");
expected = window.document.body.innerHTML;
assert.deepEqual(actual, expected, message);
@ -131,7 +137,7 @@ export function loadConfig ( file ) {
delete require.cache[resolved];
return require(resolved).default;
} catch (err) {
if ( err.code === 'E_NOT_FOUND' ) {
if (err.code === "E_NOT_FOUND") {
return {};
}
@ -140,10 +146,15 @@ export function loadConfig ( file ) {
}
export function addLineNumbers(code) {
return code.split( '\n' ).map( ( line, i ) => {
return code
.split("\n")
.map((line, i) => {
i = String(i + 1);
while (i.length < 3) i = ` ${i}`;
return `${i}: ${line.replace( /^\t+/, match => match.split( '\t' ).join( ' ' ) )}`;
}).join( '\n' );
return `${i}: ${line.replace(/^\t+/, match =>
match.split("\t").join(" ")
)}`;
})
.join("\n");
}

@ -1,23 +1,25 @@
import assert from 'assert';
import * as fs from 'fs';
import * as path from 'path';
import { rollup } from 'rollup';
import { svelte } from '../helpers.js';
import assert from "assert";
import * as fs from "fs";
import * as path from "path";
import { rollup } from "rollup";
import { svelte } from "../helpers.js";
describe( 'js', () => {
fs.readdirSync( 'test/js/samples' ).forEach( dir => {
if ( dir[0] === '.' ) return;
describe("js", () => {
fs.readdirSync("test/js/samples").forEach(dir => {
if (dir[0] === ".") return;
// add .solo to a sample directory name to only run that test
const solo = /\.solo/.test(dir);
if (solo && process.env.CI) {
throw new Error( 'Forgot to remove `solo: true` from test' );
throw new Error("Forgot to remove `solo: true` from test");
}
(solo ? it.only : it)(dir, () => {
dir = path.resolve( 'test/js/samples', dir );
const input = fs.readFileSync( `${dir}/input.html`, 'utf-8' ).replace( /\s+$/, '' );
dir = path.resolve("test/js/samples", dir);
const input = fs
.readFileSync(`${dir}/input.html`, "utf-8")
.replace(/\s+$/, "");
let actual;
@ -31,30 +33,36 @@ describe( 'js', () => {
}
fs.writeFileSync(`${dir}/_actual.js`, actual);
const expected = fs.readFileSync( `${dir}/expected.js`, 'utf-8' );
const expectedBundle = fs.readFileSync( `${dir}/expected-bundle.js`, 'utf-8' );
const expected = fs.readFileSync(`${dir}/expected.js`, "utf-8");
const expectedBundle = fs.readFileSync(
`${dir}/expected-bundle.js`,
"utf-8"
);
return rollup({
entry: `${dir}/_actual.js`,
plugins: [{
plugins: [
{
resolveId(importee, importer) {
if (!importer) return importee;
if ( importee === 'svelte/shared.js' ) return path.resolve('shared.js');
if (importee === "svelte/shared.js")
return path.resolve("shared.js");
return null;
}
}]
}
]
}).then(bundle => {
const actualBundle = bundle.generate({ format: 'es' }).code;
const actualBundle = bundle.generate({ format: "es" }).code;
fs.writeFileSync(`${dir}/_actual-bundle.js`, actualBundle);
assert.equal(
actual.trim().replace( /^\s+$/gm, '' ),
expected.trim().replace( /^\s+$/gm, '' )
actual.trim().replace(/^\s+$/gm, ""),
expected.trim().replace(/^\s+$/gm, "")
);
assert.equal(
actualBundle.trim().replace( /^\s+$/gm, '' ),
expectedBundle.trim().replace( /^\s+$/gm, '' )
actualBundle.trim().replace(/^\s+$/gm, ""),
expectedBundle.trim().replace(/^\s+$/gm, "")
);
});
});

@ -1,10 +1,13 @@
// this file will replace all the expected.js and expected-bundle.js files with
// their _actual equivalents. Only use it when you're sure that you haven't
// broken anything!
const fs = require('fs');
const glob = require('glob');
const fs = require("fs");
const glob = require("glob");
glob.sync('samples/*/_actual*', {cwd: __dirname}).forEach(file => {
const actual = fs.readFileSync(`${__dirname}/${file}`, 'utf-8');
fs.writeFileSync(`${__dirname}/${file.replace('_actual', 'expected')}`, actual);
glob.sync("samples/*/_actual*", { cwd: __dirname }).forEach(file => {
const actual = fs.readFileSync(`${__dirname}/${file}`, "utf-8");
fs.writeFileSync(
`${__dirname}/${file.replace("_actual", "expected")}`,
actual
);
});

@ -1,31 +1,38 @@
import assert from 'assert';
import * as fs from 'fs';
import { svelte } from '../helpers.js';
import assert from "assert";
import * as fs from "fs";
import { svelte } from "../helpers.js";
describe( 'parse', () => {
fs.readdirSync( 'test/parser/samples' ).forEach( dir => {
if ( dir[0] === '.' ) return;
describe("parse", () => {
fs.readdirSync("test/parser/samples").forEach(dir => {
if (dir[0] === ".") return;
// add .solo to a sample directory name to only run that test
const solo = /\.solo$/.test(dir);
if (solo && process.env.CI) {
throw new Error( `Forgot to remove '.solo' from test parser/samples/${dir}` );
throw new Error(
`Forgot to remove '.solo' from test parser/samples/${dir}`
);
}
(solo ? it.only : it)(dir, () => {
const input = fs.readFileSync( `test/parser/samples/${dir}/input.html`, 'utf-8' ).replace( /\s+$/, '' );
const input = fs
.readFileSync(`test/parser/samples/${dir}/input.html`, "utf-8")
.replace(/\s+$/, "");
try {
const actual = svelte.parse(input);
fs.writeFileSync( `test/parser/samples/${dir}/_actual.json`, JSON.stringify( actual, null, '\t' ) );
fs.writeFileSync(
`test/parser/samples/${dir}/_actual.json`,
JSON.stringify(actual, null, "\t")
);
const expected = require(`./samples/${dir}/output.json`);
assert.deepEqual(actual.html, expected.html);
assert.deepEqual(actual.css, expected.css);
assert.deepEqual(actual.js, expected.js);
} catch (err) {
if ( err.name !== 'ParseError' ) throw err;
if (err.name !== "ParseError") throw err;
try {
const expected = require(`./samples/${dir}/error.json`);
@ -34,13 +41,13 @@ describe( 'parse', () => {
assert.deepEqual(err.loc, expected.loc);
assert.equal(err.pos, expected.pos);
} catch (err2) {
throw err2.code === 'MODULE_NOT_FOUND' ? err : err2;
throw err2.code === "MODULE_NOT_FOUND" ? err : err2;
}
}
});
});
it( 'handles errors with options.onerror', () => {
it("handles errors with options.onerror", () => {
let errored = false;
svelte.compile(`<h1>unclosed`, {
@ -53,7 +60,7 @@ describe( 'parse', () => {
assert.ok(errored);
});
it( 'throws without options.onerror', () => {
it("throws without options.onerror", () => {
assert.throws(() => {
svelte.compile(`<h1>unclosed`);
}, /<h1> was left open/);

@ -1,12 +1,18 @@
import spaces from '../../src/utils/spaces.js';
import assert from 'assert';
import * as path from 'path';
import * as fs from 'fs';
import * as acorn from 'acorn';
import * as babel from 'babel-core';
import { transitionManager } from '../../shared.js';
import { addLineNumbers, loadConfig, loadSvelte, env, setupHtmlEqual } from '../helpers.js';
import spaces from "../../src/utils/spaces.js";
import assert from "assert";
import * as path from "path";
import * as fs from "fs";
import * as acorn from "acorn";
import * as babel from "babel-core";
import { transitionManager } from "../../shared.js";
import {
addLineNumbers,
loadConfig,
loadSvelte,
env,
setupHtmlEqual
} from "../helpers.js";
let svelte;
@ -14,17 +20,20 @@ let showCompiledCode = false;
let compileOptions = null;
function getName(filename) {
const base = path.basename( filename ).replace( '.html', '' );
const base = path.basename(filename).replace(".html", "");
return base[0].toUpperCase() + base.slice(1);
}
const nodeVersionMatch = /^v(\d)/.exec(process.version);
const legacy = +nodeVersionMatch[1] < 6;
const babelrc = require( '../../package.json' ).babel;
const babelrc = require("../../package.json").babel;
require.extensions[ '.html' ] = function ( module, filename ) {
const options = Object.assign({ filename, name: getName( filename ) }, compileOptions );
let { code } = svelte.compile( fs.readFileSync( filename, 'utf-8' ), options );
require.extensions[".html"] = function(module, filename) {
const options = Object.assign(
{ filename, name: getName(filename) },
compileOptions
);
let { code } = svelte.compile(fs.readFileSync(filename, "utf-8"), options);
if (showCompiledCode) console.log(addLineNumbers(code)); // eslint-disable-line no-console
@ -35,19 +44,19 @@ require.extensions[ '.html' ] = function ( module, filename ) {
const Object_assign = Object.assign;
describe( 'runtime', () => {
describe("runtime", () => {
before(() => {
svelte = loadSvelte(true);
return setupHtmlEqual();
});
function runTest(dir, shared) {
if ( dir[0] === '.' ) return;
if (dir[0] === ".") return;
const config = loadConfig(`./runtime/samples/${dir}/_config.js`);
if (config.solo && process.env.CI) {
throw new Error( 'Forgot to remove `solo: true` from test' );
throw new Error("Forgot to remove `solo: true` from test");
}
(config.skip ? it.skip : config.solo ? it.only : it)(dir, () => {
@ -59,7 +68,10 @@ describe( 'runtime', () => {
compileOptions.dev = config.dev;
try {
const source = fs.readFileSync( `test/runtime/samples/${dir}/main.html`, 'utf-8' );
const source = fs.readFileSync(
`test/runtime/samples/${dir}/main.html`,
"utf-8"
);
compiled = svelte.compile(source, compileOptions);
} catch (err) {
if (config.compileError) {
@ -75,9 +87,12 @@ describe( 'runtime', () => {
// check that no ES2015+ syntax slipped in
if (!config.allowES2015) {
try {
const startIndex = code.indexOf( 'function create_main_fragment' ); // may change!
if ( startIndex === -1 ) throw new Error( 'missing create_main_fragment' );
const es5 = spaces( startIndex ) + code.slice( startIndex ).replace( /export default .+/, '' );
const startIndex = code.indexOf("function create_main_fragment"); // may change!
if (startIndex === -1)
throw new Error("missing create_main_fragment");
const es5 =
spaces(startIndex) +
code.slice(startIndex).replace(/export default .+/, "");
acorn.parse(es5, { ecmaVersion: 5 });
} catch (err) {
if (!config.show) console.log(addLineNumbers(code)); // eslint-disable-line no-console
@ -85,7 +100,9 @@ describe( 'runtime', () => {
}
}
Object.keys( require.cache ).filter( x => x.endsWith( '.html' ) ).forEach( file => {
Object.keys(require.cache)
.filter(x => x.endsWith(".html"))
.forEach(file => {
delete require.cache[file];
});
@ -128,7 +145,9 @@ describe( 'runtime', () => {
}
Object.assign = () => {
throw new Error( 'cannot use Object.assign in generated code, as it is not supported everywhere' );
throw new Error(
"cannot use Object.assign in generated code, as it is not supported everywhere"
);
};
global.window = window;
@ -136,7 +155,7 @@ describe( 'runtime', () => {
// Put the constructor on window for testing
window.SvelteComponent = SvelteComponent;
const target = window.document.querySelector( 'main' );
const target = window.document.querySelector("main");
const warnings = [];
const warn = console.warn;
@ -155,14 +174,14 @@ describe( 'runtime', () => {
if (config.error) {
unintendedError = true;
throw new Error( 'Expected a runtime error' );
throw new Error("Expected a runtime error");
}
if (config.warnings) {
assert.deepEqual(warnings, config.warnings);
} else if (warnings.length) {
unintendedError = true;
throw new Error( 'Received unexpected warnings' );
throw new Error("Received unexpected warnings");
}
if (config.html) {
@ -175,7 +194,7 @@ describe( 'runtime', () => {
config.test(assert, component, target, window, raf);
} else {
component.destroy();
assert.equal( target.innerHTML, '' );
assert.equal(target.innerHTML, "");
}
})
.catch(err => {
@ -183,9 +202,7 @@ describe( 'runtime', () => {
if (config.error && !unintendedError) {
config.error(assert, err);
}
else {
} else {
if (!config.show) console.log(addLineNumbers(code)); // eslint-disable-line no-console
throw err;
}
@ -193,27 +210,29 @@ describe( 'runtime', () => {
});
}
describe( 'inline helpers', () => {
fs.readdirSync( 'test/runtime/samples' ).forEach( dir => {
describe("inline helpers", () => {
fs.readdirSync("test/runtime/samples").forEach(dir => {
runTest(dir, null);
});
});
const shared = path.resolve( 'shared.js' );
describe( 'shared helpers', () => {
fs.readdirSync( 'test/runtime/samples' ).forEach( dir => {
const shared = path.resolve("shared.js");
describe("shared helpers", () => {
fs.readdirSync("test/runtime/samples").forEach(dir => {
runTest(dir, shared);
});
});
it( 'fails if options.target is missing in dev mode', () => {
it("fails if options.target is missing in dev mode", () => {
const { code } = svelte.compile(`<div></div>`, {
format: 'iife',
name: 'SvelteComponent',
format: "iife",
name: "SvelteComponent",
dev: true
});
const SvelteComponent = eval( `(function () { ${code}; return SvelteComponent; }())` );
const SvelteComponent = eval(
`(function () { ${code}; return SvelteComponent; }())`
);
assert.throws(() => {
new SvelteComponent();

@ -1,14 +1,20 @@
import assert from 'assert';
import * as fs from 'fs';
import * as path from 'path';
import { addLineNumbers, loadConfig, setupHtmlEqual, svelte, tryToLoadJson } from '../helpers.js';
import assert from "assert";
import * as fs from "fs";
import * as path from "path";
import {
addLineNumbers,
loadConfig,
setupHtmlEqual,
svelte,
tryToLoadJson
} from "../helpers.js";
function tryToReadFile(file) {
try {
return fs.readFileSync( file, 'utf-8' );
return fs.readFileSync(file, "utf-8");
} catch (err) {
if ( err.code !== 'ENOENT' ) throw err;
if (err.code !== "ENOENT") throw err;
return null;
}
}
@ -17,17 +23,17 @@ function capitalize ( str ) {
return str[0].toUpperCase() + str.slice(1);
}
describe( 'ssr', () => {
describe("ssr", () => {
before(() => {
require( process.env.COVERAGE ?
'../../src/server-side-rendering/register.js' :
'../../ssr/register' );
require(process.env.COVERAGE
? "../../src/server-side-rendering/register.js"
: "../../ssr/register");
return setupHtmlEqual();
});
fs.readdirSync( 'test/server-side-rendering/samples' ).forEach( dir => {
if ( dir[0] === '.' ) return;
fs.readdirSync("test/server-side-rendering/samples").forEach(dir => {
if (dir[0] === ".") return;
// add .solo to a sample directory name to only run that test, or
// .show to always show the output. or both
@ -35,15 +41,15 @@ describe( 'ssr', () => {
let show = /\.show/.test(dir);
if (solo && process.env.CI) {
throw new Error( 'Forgot to remove `solo: true` from test' );
throw new Error("Forgot to remove `solo: true` from test");
}
(solo ? it.only : it)(dir, () => {
dir = path.resolve( 'test/server-side-rendering/samples', dir );
dir = path.resolve("test/server-side-rendering/samples", dir);
const component = require(`${dir}/main.html`);
const expectedHtml = tryToReadFile(`${dir}/_expected.html`);
const expectedCss = tryToReadFile( `${dir}/_expected.css` ) || '';
const expectedCss = tryToReadFile(`${dir}/_expected.css`) || "";
const data = tryToLoadJson(`${dir}/data.json`);
let html;
@ -60,10 +66,10 @@ describe( 'ssr', () => {
if (show) {
fs.readdirSync(dir).forEach(file => {
if ( file[0] === '_' ) return;
const source = fs.readFileSync( `${dir}/${file}`, 'utf-8' );
if (file[0] === "_") return;
const source = fs.readFileSync(`${dir}/${file}`, "utf-8");
const name = capitalize(file.slice(0, -path.extname(file).length));
const { code } = svelte.compile( source, { generate: 'ssr', name });
const { code } = svelte.compile(source, { generate: "ssr", name });
console.group(file);
console.log(addLineNumbers(code));
console.groupEnd();
@ -76,28 +82,34 @@ describe( 'ssr', () => {
if (css) fs.writeFileSync(`${dir}/_actual.css`, css);
assert.htmlEqual(html, expectedHtml);
assert.equal( css.replace( /^\s+/gm, '' ), expectedCss.replace( /^\s+/gm, '' ) );
assert.equal(
css.replace(/^\s+/gm, ""),
expectedCss.replace(/^\s+/gm, "")
);
});
});
// duplicate client-side tests, as far as possible
fs.readdirSync( 'test/runtime/samples' ).forEach( dir => {
if ( dir[0] === '.' ) return;
fs.readdirSync("test/runtime/samples").forEach(dir => {
if (dir[0] === ".") return;
const config = loadConfig(`./runtime/samples/${dir}/_config.js`);
if (config.solo && process.env.CI) {
throw new Error( 'Forgot to remove `solo: true` from test' );
throw new Error("Forgot to remove `solo: true` from test");
}
if ( config['skip-ssr'] ) return;
if (config["skip-ssr"]) return;
(config.skip ? it.skip : config.solo ? it.only : it)(dir, () => {
let compiled;
try {
const source = fs.readFileSync( `test/runtime/samples/${dir}/main.html`, 'utf-8' );
compiled = svelte.compile( source, { generate: 'ssr' });
const source = fs.readFileSync(
`test/runtime/samples/${dir}/main.html`,
"utf-8"
);
compiled = svelte.compile(source, { generate: "ssr" });
} catch (err) {
if (config.compileError) {
config.compileError(err);

@ -1,9 +1,9 @@
const nodeVersionMatch = /^v(\d)/.exec(process.version);
const legacy = +nodeVersionMatch[1] < 6;
const babelrc = require( '../package.json' ).babel;
const babelrc = require("../package.json").babel;
if (legacy) {
require( 'babel-register' )( babelrc );
require("babel-register")(babelrc);
} else {
require( 'reify' );
require("reify");
}

@ -1,34 +1,44 @@
import * as fs from 'fs';
import * as path from 'path';
import assert from 'assert';
import { svelte, exists } from '../helpers.js';
import { SourceMapConsumer } from 'source-map';
import { getLocator } from 'locate-character';
import * as fs from "fs";
import * as path from "path";
import assert from "assert";
import { svelte, exists } from "../helpers.js";
import { SourceMapConsumer } from "source-map";
import { getLocator } from "locate-character";
describe( 'sourcemaps', () => {
fs.readdirSync( 'test/sourcemaps/samples' ).forEach( dir => {
if ( dir[0] === '.' ) return;
describe("sourcemaps", () => {
fs.readdirSync("test/sourcemaps/samples").forEach(dir => {
if (dir[0] === ".") return;
const solo = exists(`test/sourcemaps/samples/${dir}/solo`);
if (solo && process.env.CI) {
throw new Error( 'Forgot to remove `solo: true` from test' );
throw new Error("Forgot to remove `solo: true` from test");
}
(solo ? it.only : it)(dir, () => {
const filename = path.resolve( `test/sourcemaps/samples/${dir}/input.html` );
const outputFilename = path.resolve( `test/sourcemaps/samples/${dir}/output.js` );
const input = fs.readFileSync( filename, 'utf-8' ).replace( /\s+$/, '' );
const filename = path.resolve(
`test/sourcemaps/samples/${dir}/input.html`
);
const outputFilename = path.resolve(
`test/sourcemaps/samples/${dir}/output.js`
);
const input = fs.readFileSync(filename, "utf-8").replace(/\s+$/, "");
const { code, map } = svelte.compile(input, {
filename,
outputFilename
});
fs.writeFileSync( outputFilename, `${code}\n//# sourceMappingURL=output.js.map` );
fs.writeFileSync( `${outputFilename}.map`, JSON.stringify( map, null, ' ' ) );
fs.writeFileSync(
outputFilename,
`${code}\n//# sourceMappingURL=output.js.map`
);
fs.writeFileSync(
`${outputFilename}.map`,
JSON.stringify(map, null, " ")
);
assert.deepEqual( map.sources, [ 'input.html' ]);
assert.deepEqual(map.sources, ["input.html"]);
const { test } = require(`./samples/${dir}/test.js`);

@ -1,11 +1,11 @@
const glob = require( 'glob' );
const glob = require("glob");
require( './setup' );
require("./setup");
glob.sync( '**/__test__.js', { cwd: 'src' }).forEach( function ( file ) {
require( '../src/' + file );
glob.sync("**/__test__.js", { cwd: "src" }).forEach(function(file) {
require("../src/" + file);
});
glob.sync( '*/index.js', { cwd: 'test' }).forEach( function ( file ) {
require( './' + file );
glob.sync("*/index.js", { cwd: "test" }).forEach(function(file) {
require("./" + file);
});

@ -1,21 +1,21 @@
import * as fs from 'fs';
import assert from 'assert';
import { svelte, tryToLoadJson } from '../helpers.js';
import * as fs from "fs";
import assert from "assert";
import { svelte, tryToLoadJson } from "../helpers.js";
describe( 'validate', () => {
fs.readdirSync( 'test/validator/samples' ).forEach( dir => {
if ( dir[0] === '.' ) return;
describe("validate", () => {
fs.readdirSync("test/validator/samples").forEach(dir => {
if (dir[0] === ".") return;
// add .solo to a sample directory name to only run that test
const solo = /\.solo/.test(dir);
if (solo && process.env.CI) {
throw new Error( 'Forgot to remove `solo: true` from test' );
throw new Error("Forgot to remove `solo: true` from test");
}
(solo ? it.only : it)(dir, () => {
const filename = `test/validator/samples/${dir}/input.html`;
const input = fs.readFileSync( filename, 'utf-8' ).replace( /\s+$/, '' );
const input = fs.readFileSync(filename, "utf-8").replace(/\s+$/, "");
try {
const parsed = svelte.parse(input);
@ -41,13 +41,15 @@ describe( 'validate', () => {
}
});
const expectedErrors = tryToLoadJson( `test/validator/samples/${dir}/errors.json` ) || [];
const expectedWarnings = tryToLoadJson( `test/validator/samples/${dir}/warnings.json` ) || [];
const expectedErrors =
tryToLoadJson(`test/validator/samples/${dir}/errors.json`) || [];
const expectedWarnings =
tryToLoadJson(`test/validator/samples/${dir}/warnings.json`) || [];
assert.deepEqual(errors, expectedErrors);
assert.deepEqual(warnings, expectedWarnings);
} catch (err) {
if ( err.name !== 'ParseError' ) throw err;
if (err.name !== "ParseError") throw err;
try {
const expected = require(`./samples/${dir}/errors.json`)[0];
@ -56,24 +58,24 @@ describe( 'validate', () => {
assert.deepEqual(err.loc, expected.loc);
assert.equal(err.pos, expected.pos);
} catch (err2) {
throw err2.code === 'MODULE_NOT_FOUND' ? err : err2;
throw err2.code === "MODULE_NOT_FOUND" ? err : err2;
}
}
});
});
it( 'errors if options.name is illegal', () => {
it("errors if options.name is illegal", () => {
assert.throws(() => {
svelte.compile( '<div></div>', {
name: 'not.valid'
svelte.compile("<div></div>", {
name: "not.valid"
});
}, /options\.name must be a valid identifier/);
});
it( 'warns if options.name is not capitalised', () => {
it("warns if options.name is not capitalised", () => {
const warnings = [];
svelte.compile( '<div></div>', {
name: 'lowercase',
svelte.compile("<div></div>", {
name: "lowercase",
onwarn(warning) {
warnings.push({
message: warning.message,
@ -82,6 +84,12 @@ describe( 'validate', () => {
});
}
});
assert.deepEqual( warnings, [ { message: 'options.name should be capitalised', pos: undefined, loc: undefined } ] );
assert.deepEqual(warnings, [
{
message: "options.name should be capitalised",
pos: undefined,
loc: undefined
}
]);
});
});

Loading…
Cancel
Save