prettierfy test files

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

@ -1,40 +1,40 @@
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>
`;
const component = svelte.create( source );
assert( component instanceof Function );
const component = svelte.create(source);
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>
`;
const component = svelte.create( source, {
const component = svelte.create(source, {
onerror: () => {
done();
}
});
assert.equal( component, undefined );
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>
`;
const component = svelte.create( source, {
const component = svelte.create(source, {
onerror: () => {}
});
assert.equal( component, undefined );
assert.equal(component, undefined);
});
});

@ -1,36 +1,41 @@
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 ) {
function tryRequire(file) {
try {
return require( file ).default;
} catch ( err ) {
if ( err.code !== 'MODULE_NOT_FOUND' ) throw err;
return require(file).default;
} catch (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 );
const solo = /\.solo/.test(dir);
if ( solo && process.env.CI ) {
throw new Error( 'Forgot to remove `solo: true` from test' );
if (solo && process.env.CI) {
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+$/, '' );
(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 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 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"
);
assert.equal( actual.trim(), expected.trim() );
assert.equal(actual.trim(), expected.trim());
});
});
});

@ -1,88 +1,94 @@
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 );
function testAmd(code, expectedId, dependencies, html) {
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 ) );
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 );
assert.htmlEqual(main.innerHTML, html);
component.destroy();
}
define.amd = true;
fn( define );
fn(define);
});
}
function testCjs ( code, dependencyById, html ) {
const fn = new Function( 'module', 'exports', 'require', code );
function testCjs(code, dependencyById, html) {
const fn = new Function("module", "exports", "require", code);
return env().then( window => {
return env().then(window => {
const module = { exports: {} };
const require = id => {
return dependencyById[ id ];
return dependencyById[id];
};
fn( module, module.exports, require );
fn(module, module.exports, require);
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 );
assert.htmlEqual(main.innerHTML, html);
component.destroy();
});
}
function testIife ( code, name, globals, html ) {
const fn = new Function( Object.keys( globals ), `${code}\n\nreturn ${name};` );
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 ] ) );
return env().then(window => {
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 );
assert.htmlEqual(main.innerHTML, html);
component.destroy();
});
}
function testEval ( code, name, globals, html ) {
const fn = new Function( Object.keys( globals ), `return ${code};` );
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 ] ) );
return env().then(window => {
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 );
assert.htmlEqual(main.innerHTML, html);
component.destroy();
});
}
describe( 'formats', () => {
before( setupHtmlEqual );
describe("formats", () => {
before(setupHtmlEqual);
describe( 'amd', () => {
it( 'generates an AMD module', () => {
describe("amd", () => {
it("generates an AMD module", () => {
const source = deindent`
<div>{{answer}}</div>
@ -97,17 +103,17 @@ describe( 'formats', () => {
</script>
`;
const { code } = svelte.compile( source, {
format: 'amd',
amd: { id: 'foo' }
const { code } = svelte.compile(source, {
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>
@ -122,16 +128,16 @@ describe( 'formats', () => {
</script>
`;
const { code } = svelte.compile( source, {
format: 'cjs'
const { code } = svelte.compile(source, {
format: "cjs"
});
return testCjs( code, { answer: 42 }, `<div>42</div>` );
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>
@ -146,20 +152,20 @@ describe( 'formats', () => {
</script>
`;
const { code } = svelte.compile( source, {
format: 'iife',
name: 'Foo',
const { code } = svelte.compile(source, {
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>
@ -174,25 +180,25 @@ describe( 'formats', () => {
</script>
`;
const { code } = svelte.compile( source, {
format: 'umd',
name: 'Foo',
const { code } = svelte.compile(source, {
format: "umd",
name: "Foo",
globals: {
answer: 'answer'
answer: "answer"
},
amd: {
id: 'foo'
id: "foo"
}
});
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>` ) );
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>`));
});
});
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>
@ -207,14 +213,14 @@ describe( 'formats', () => {
</script>
`;
const { code } = svelte.compile( source, {
format: 'eval',
const { code } = svelte.compile(source, {
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,137 +1,143 @@
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,
// but for sanity purposes, we need to test dist files
export function loadSvelte ( test ) {
if ( test ) global.__svelte_test = true;
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 );
delete require.cache[resolved];
return require(resolved);
}
export const svelte = loadSvelte();
export function exists ( path ) {
export function exists(path) {
try {
fs.statSync( path );
fs.statSync(path);
return true;
} catch ( err ) {
} catch (err) {
return false;
}
}
export function tryToLoadJson ( file ) {
export function tryToLoadJson(file) {
try {
return JSON.parse( fs.readFileSync( file ) );
} catch ( err ) {
if ( err.code !== 'ENOENT' ) throw err;
return JSON.parse(fs.readFileSync(file));
} catch (err) {
if (err.code !== "ENOENT") throw err;
return null;
}
}
export function tryToReadFile ( file ) {
export function tryToReadFile(file) {
try {
return fs.readFileSync( file, 'utf-8' );
} catch ( err ) {
if ( err.code !== 'ENOENT' ) throw err;
return fs.readFileSync(file, "utf-8");
} catch (err) {
if (err.code !== "ENOENT") throw err;
return null;
}
}
export function env () {
return new Promise( ( fulfil, reject ) => {
jsdom.env( '<main></main>', ( err, window ) => {
if ( err ) {
reject( err );
export function env() {
return new Promise((fulfil, reject) => {
jsdom.env("<main></main>", (err, window) => {
if (err) {
reject(err);
} else {
global.document = window.document;
fulfil( window );
fulfil(window);
}
});
});
}
function cleanChildren ( node ) {
function cleanChildren(node) {
let previous = null;
[ ...node.childNodes ].forEach( child => {
if ( child.nodeType === 8 ) {
[...node.childNodes].forEach(child => {
if (child.nodeType === 8) {
// comment
node.removeChild( child );
node.removeChild(child);
return;
}
if ( child.nodeType === 3 ) {
if ( node.namespaceURI === 'http://www.w3.org/2000/svg' && node.tagName !== 'text' && node.tagName !== 'tspan' ) {
node.removeChild( child );
if (child.nodeType === 3) {
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 ) {
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 );
node.removeChild(child);
child = previous;
}
}
else {
cleanChildren( child );
} else {
cleanChildren(child);
}
previous = child;
});
// collapse whitespace
if ( node.firstChild && node.firstChild.nodeType === 3 ) {
node.firstChild.data = node.firstChild.data.replace( /^\s+/, '' );
if ( !node.firstChild.data ) node.removeChild( node.firstChild );
if (node.firstChild && node.firstChild.nodeType === 3) {
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+$/, '' );
if ( !node.lastChild.data ) node.removeChild( node.lastChild );
if (node.lastChild && node.lastChild.nodeType === 3) {
node.lastChild.data = node.lastChild.data.replace(/\s+$/, "");
if (!node.lastChild.data) node.removeChild(node.lastChild);
}
}
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, '' );
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, "");
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 );
assert.deepEqual(actual, expected, message);
};
});
}
export function loadConfig ( file ) {
export function loadConfig(file) {
try {
const resolved = require.resolve( file );
delete require.cache[ resolved ];
return require( resolved ).default;
} catch ( err ) {
if ( err.code === 'E_NOT_FOUND' ) {
const resolved = require.resolve(file);
delete require.cache[resolved];
return require(resolved).default;
} catch (err) {
if (err.code === "E_NOT_FOUND") {
return {};
}
@ -139,11 +145,16 @@ export function loadConfig ( file ) {
}
}
export function addLineNumbers ( code ) {
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' );
export function addLineNumbers(code) {
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");
}

@ -1,60 +1,68 @@
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 );
const solo = /\.solo/.test(dir);
if ( solo && process.env.CI ) {
throw new Error( 'Forgot to remove `solo: true` from test' );
if (solo && process.env.CI) {
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+$/, '' );
(solo ? it.only : it)(dir, () => {
dir = path.resolve("test/js/samples", dir);
const input = fs
.readFileSync(`${dir}/input.html`, "utf-8")
.replace(/\s+$/, "");
let actual;
try {
actual = svelte.compile( input, {
actual = svelte.compile(input, {
shared: true
}).code;
} catch ( err ) {
console.log( err.frame );
} catch (err) {
console.log(err.frame);
throw err;
}
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' );
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"
);
return rollup({
entry: `${dir}/_actual.js`,
plugins: [{
resolveId ( importee, importer ) {
if ( !importer ) return importee;
if ( importee === 'svelte/shared.js' ) return path.resolve('shared.js');
return null;
plugins: [
{
resolveId(importee, importer) {
if (!importer) return importee;
if (importee === "svelte/shared.js")
return path.resolve("shared.js");
return null;
}
}
}]
]
}).then(bundle => {
const actualBundle = bundle.generate({ format: 'es' }).code;
fs.writeFileSync( `${dir}/_actual-bundle.js`, actualBundle );
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,61 +1,68 @@
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 );
const solo = /\.solo$/.test(dir);
if ( solo && process.env.CI ) {
throw new Error( `Forgot to remove '.solo' from test parser/samples/${dir}` );
if (solo && process.env.CI) {
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+$/, '' );
(solo ? it.only : it)(dir, () => {
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' ) );
const expected = require( `./samples/${dir}/output.json` );
const actual = svelte.parse(input);
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;
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;
try {
const expected = require( `./samples/${dir}/error.json` );
const expected = require(`./samples/${dir}/error.json`);
assert.equal( err.message, expected.message );
assert.deepEqual( err.loc, expected.loc );
assert.equal( err.pos, expected.pos );
} catch ( err2 ) {
throw err2.code === 'MODULE_NOT_FOUND' ? err : err2;
assert.equal(err.message, expected.message);
assert.deepEqual(err.loc, expected.loc);
assert.equal(err.pos, expected.pos);
} catch (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`, {
onerror ( err ) {
svelte.compile(`<h1>unclosed`, {
onerror(err) {
errored = true;
assert.equal( err.message, `<h1> was left open` );
assert.equal(err.message, `<h1> was left open`);
}
});
assert.ok( errored );
assert.ok(errored);
});
it( 'throws without options.onerror', () => {
assert.throws( () => {
svelte.compile( `<h1>unclosed` );
}, /<h1> was left open/ );
it("throws without options.onerror", () => {
assert.throws(() => {
svelte.compile(`<h1>unclosed`);
}, /<h1> was left open/);
});
});

@ -1,56 +1,65 @@
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;
let showCompiledCode = false;
let compileOptions = null;
function getName ( filename ) {
const base = path.basename( filename ).replace( '.html', '' );
return base[0].toUpperCase() + base.slice( 1 );
function getName(filename) {
const base = path.basename(filename).replace(".html", "");
return base[0].toUpperCase() + base.slice(1);
}
const nodeVersionMatch = /^v(\d)/.exec( process.version );
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
if (showCompiledCode) console.log(addLineNumbers(code)); // eslint-disable-line no-console
if ( legacy ) code = babel.transform( code, babelrc ).code;
if (legacy) code = babel.transform(code, babelrc).code;
return module._compile( code, filename );
return module._compile(code, filename);
};
const Object_assign = Object.assign;
describe( 'runtime', () => {
before( () => {
svelte = loadSvelte( true );
describe("runtime", () => {
before(() => {
svelte = loadSvelte(true);
return setupHtmlEqual();
});
function runTest ( dir, shared ) {
if ( dir[0] === '.' ) return;
function runTest(dir, shared) {
if (dir[0] === ".") return;
const config = loadConfig( `./runtime/samples/${dir}/_config.js` );
const config = loadConfig(`./runtime/samples/${dir}/_config.js`);
if ( config.solo && process.env.CI ) {
throw new Error( 'Forgot to remove `solo: true` from test' );
if (config.solo && process.env.CI) {
throw new Error("Forgot to remove `solo: true` from test");
}
( config.skip ? it.skip : config.solo ? it.only : it )( dir, () => {
(config.skip ? it.skip : config.solo ? it.only : it)(dir, () => {
let compiled;
showCompiledCode = config.show;
@ -59,11 +68,14 @@ describe( 'runtime', () => {
compileOptions.dev = config.dev;
try {
const source = fs.readFileSync( `test/runtime/samples/${dir}/main.html`, 'utf-8' );
compiled = svelte.compile( source, compileOptions );
} catch ( err ) {
if ( config.compileError ) {
config.compileError( err );
const source = fs.readFileSync(
`test/runtime/samples/${dir}/main.html`,
"utf-8"
);
compiled = svelte.compile(source, compileOptions);
} catch (err) {
if (config.compileError) {
config.compileError(err);
return;
} else {
throw err;
@ -73,28 +85,33 @@ describe( 'runtime', () => {
const { code } = compiled;
// check that no ES2015+ syntax slipped in
if ( !config.allowES2015 ) {
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 .+/, '' );
acorn.parse( es5, { ecmaVersion: 5 });
} catch ( err ) {
if ( !config.show ) console.log( addLineNumbers( code ) ); // eslint-disable-line no-console
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
throw err;
}
}
Object.keys( require.cache ).filter( x => x.endsWith( '.html' ) ).forEach( file => {
delete require.cache[ file ];
});
Object.keys(require.cache)
.filter(x => x.endsWith(".html"))
.forEach(file => {
delete require.cache[file];
});
let SvelteComponent;
let unintendedError = null;
return env()
.then( window => {
.then(window => {
// set of hacks to support transition tests
transitionManager.running = false;
transitionManager.transitions = [];
@ -104,14 +121,14 @@ describe( 'runtime', () => {
callback: null,
tick: now => {
raf.time = now;
if ( raf.callback ) raf.callback();
if (raf.callback) raf.callback();
}
};
window.performance = { now: () => raf.time };
global.requestAnimationFrame = cb => {
let called = false;
raf.callback = () => {
if ( !called ) {
if (!called) {
called = true;
cb();
}
@ -121,14 +138,16 @@ describe( 'runtime', () => {
global.window = window;
try {
SvelteComponent = require( `./samples/${dir}/main.html` ).default;
} catch ( err ) {
if ( !config.show ) console.log( addLineNumbers( code ) ); // eslint-disable-line no-console
SvelteComponent = require(`./samples/${dir}/main.html`).default;
} catch (err) {
if (!config.show) console.log(addLineNumbers(code)); // eslint-disable-line no-console
throw err;
}
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,12 +155,12 @@ 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;
console.warn = warning => {
warnings.push( warning );
warnings.push(warning);
};
const component = new SvelteComponent({
@ -153,70 +172,70 @@ describe( 'runtime', () => {
console.warn = warn;
if ( config.error ) {
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 ) {
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 ) {
assert.htmlEqual( target.innerHTML, config.html );
if (config.html) {
assert.htmlEqual(target.innerHTML, config.html);
}
Object.assign = Object_assign;
if ( config.test ) {
config.test( assert, component, target, window, raf );
if (config.test) {
config.test(assert, component, target, window, raf);
} else {
component.destroy();
assert.equal( target.innerHTML, '' );
assert.equal(target.innerHTML, "");
}
})
.catch( err => {
.catch(err => {
Object.assign = Object_assign;
if ( config.error && !unintendedError ) {
config.error( assert, err );
}
else {
if ( !config.show ) console.log( addLineNumbers( code ) ); // eslint-disable-line no-console
if (config.error && !unintendedError) {
config.error(assert, err);
} else {
if (!config.show) console.log(addLineNumbers(code)); // eslint-disable-line no-console
throw err;
}
});
});
}
describe( 'inline helpers', () => {
fs.readdirSync( 'test/runtime/samples' ).forEach( dir => {
runTest( dir, null );
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 => {
runTest( dir, shared );
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', () => {
const { code } = svelte.compile( `<div></div>`, {
format: 'iife',
name: 'SvelteComponent',
it("fails if options.target is missing in dev mode", () => {
const { code } = svelte.compile(`<div></div>`, {
format: "iife",
name: "SvelteComponent",
dev: true
});
const SvelteComponent = eval( `(function () { ${code}; return SvelteComponent; }())` );
const SvelteComponent = eval(
`(function () { ${code}; return SvelteComponent; }())`
);
assert.throws( () => {
assert.throws(() => {
new SvelteComponent();
}, /'target' is a required option/ );
}, /'target' is a required option/);
});
});

@ -1,128 +1,140 @@
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 ) {
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' );
} catch ( err ) {
if ( err.code !== 'ENOENT' ) throw err;
return fs.readFileSync(file, "utf-8");
} catch (err) {
if (err.code !== "ENOENT") throw err;
return null;
}
}
function capitalize ( str ) {
return str[0].toUpperCase() + str.slice( 1 );
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
describe( 'ssr', () => {
before( () => {
require( process.env.COVERAGE ?
'../../src/server-side-rendering/register.js' :
'../../ssr/register' );
describe("ssr", () => {
before(() => {
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
const solo = /\.solo/.test( dir );
let show = /\.show/.test( dir );
const solo = /\.solo/.test(dir);
let show = /\.show/.test(dir);
if ( solo && process.env.CI ) {
throw new Error( 'Forgot to remove `solo: true` from test' );
if (solo && process.env.CI) {
throw new Error("Forgot to remove `solo: true` from test");
}
( solo ? it.only : it )( dir, () => {
dir = path.resolve( 'test/server-side-rendering/samples', dir );
const component = require( `${dir}/main.html` );
(solo ? it.only : it)(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 expectedHtml = tryToReadFile(`${dir}/_expected.html`);
const expectedCss = tryToReadFile(`${dir}/_expected.css`) || "";
const data = tryToLoadJson( `${dir}/data.json` );
const data = tryToLoadJson(`${dir}/data.json`);
let html;
let css;
let error;
try {
html = component.render( data );
html = component.render(data);
css = component.renderCss().css;
} catch ( e ) {
} catch (e) {
show = true;
error = e;
}
if ( show ) {
fs.readdirSync( dir ).forEach( file => {
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 });
console.group( file );
console.log( addLineNumbers( code ) );
if (show) {
fs.readdirSync(dir).forEach(file => {
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 });
console.group(file);
console.log(addLineNumbers(code));
console.groupEnd();
});
}
if ( error ) throw error;
if (error) throw error;
fs.writeFileSync( `${dir}/_actual.html`, html );
if ( css ) fs.writeFileSync( `${dir}/_actual.css`, css );
fs.writeFileSync(`${dir}/_actual.html`, html);
if (css) fs.writeFileSync(`${dir}/_actual.css`, css);
assert.htmlEqual( html, expectedHtml );
assert.equal( css.replace( /^\s+/gm, '' ), expectedCss.replace( /^\s+/gm, '' ) );
assert.htmlEqual(html, expectedHtml);
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` );
const config = loadConfig(`./runtime/samples/${dir}/_config.js`);
if ( config.solo && process.env.CI ) {
throw new Error( 'Forgot to remove `solo: true` from test' );
if (config.solo && process.env.CI) {
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, () => {
(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' });
} catch ( err ) {
if ( config.compileError ) {
config.compileError( err );
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);
return;
} else {
throw err;
}
}
fs.readdirSync( `test/runtime/samples/${dir}` ).forEach( file => {
const resolved = require.resolve( `../runtime/samples/${dir}/${file}` );
delete require.cache[ resolved ];
fs.readdirSync(`test/runtime/samples/${dir}`).forEach(file => {
const resolved = require.resolve(`../runtime/samples/${dir}/${file}`);
delete require.cache[resolved];
});
const component = require( `../runtime/samples/${dir}/main.html` );
const component = require(`../runtime/samples/${dir}/main.html`);
let html;
try {
html = component.render( config.data );
html = component.render(config.data);
if ( config.html ) {
assert.htmlEqual( html, config.html );
if (config.html) {
assert.htmlEqual(html, config.html);
}
} catch ( err ) {
console.log( addLineNumbers( compiled.code ) ); // eslint-disable-line no-console
} catch (err) {
console.log(addLineNumbers(compiled.code)); // eslint-disable-line no-console
throw err;
}
});

@ -1,9 +1,9 @@
const nodeVersionMatch = /^v(\d)/.exec( process.version );
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 );
if (legacy) {
require("babel-register")(babelrc);
} else {
require( 'reify' );
}
require("reify");
}

@ -1,41 +1,51 @@
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` );
const solo = exists(`test/sourcemaps/samples/${dir}/solo`);
if ( solo && process.env.CI ) {
throw new Error( 'Forgot to remove `solo: true` from test' );
if (solo && process.env.CI) {
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` );
(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 { code, map } = svelte.compile( input, {
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` );
const { test } = require(`./samples/${dir}/test.js`);
const smc = new SourceMapConsumer( map );
const smc = new SourceMapConsumer(map);
const locateInSource = getLocator( input );
const locateInGenerated = getLocator( code );
const locateInSource = getLocator(input);
const locateInGenerated = getLocator(code);
test({ assert, code, map, smc, locateInSource, locateInGenerated });
});

@ -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,30 +1,30 @@
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 );
const solo = /\.solo/.test(dir);
if ( solo && process.env.CI ) {
throw new Error( 'Forgot to remove `solo: true` from test' );
if (solo && process.env.CI) {
throw new Error("Forgot to remove `solo: true` from test");
}
( solo ? it.only : it )( dir, () => {
(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 );
const parsed = svelte.parse(input);
const errors = [];
const warnings = [];
svelte.validate( parsed, input, {
onerror ( error ) {
svelte.validate(parsed, input, {
onerror(error) {
errors.push({
message: error.message,
pos: error.pos,
@ -32,7 +32,7 @@ describe( 'validate', () => {
});
},
onwarn ( warning ) {
onwarn(warning) {
warnings.push({
message: warning.message,
pos: warning.pos,
@ -41,40 +41,42 @@ 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;
assert.deepEqual(errors, expectedErrors);
assert.deepEqual(warnings, expectedWarnings);
} catch (err) {
if (err.name !== "ParseError") throw err;
try {
const expected = require( `./samples/${dir}/errors.json` )[0];
const expected = require(`./samples/${dir}/errors.json`)[0];
assert.equal( err.message, expected.message );
assert.deepEqual( err.loc, expected.loc );
assert.equal( err.pos, expected.pos );
} catch ( err2 ) {
throw err2.code === 'MODULE_NOT_FOUND' ? err : err2;
assert.equal(err.message, expected.message);
assert.deepEqual(err.loc, expected.loc);
assert.equal(err.pos, expected.pos);
} catch (err2) {
throw err2.code === "MODULE_NOT_FOUND" ? err : err2;
}
}
});
});
it( 'errors if options.name is illegal', () => {
assert.throws( () => {
svelte.compile( '<div></div>', {
name: 'not.valid'
it("errors if options.name is illegal", () => {
assert.throws(() => {
svelte.compile("<div></div>", {
name: "not.valid"
});
}, /options\.name must be a valid identifier/ );
}, /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',
onwarn ( warning ) {
svelte.compile("<div></div>", {
name: "lowercase",
onwarn(warning) {
warnings.push({
message: warning.message,
pos: warning.pos,
@ -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