Migrate a few packages' tests to use Jest Expect (see below)

* Migrate the following packages' tests:
    * babel-helper-annotate-as-pure
    * babel-helper-module-imports
    * babel-helper-transform-fixture-test-runner
    * babel-highlight
    * babel-node
    * babel-plugin-transform-modules-commonjs
    * babel-preset-env-standalone
    * babel-preset-env
    * babel-preset-es2015
    * babel-preset-react
    * babel-standalone
    * babel-template
    * babel-traverse
    * babel-types
This commit is contained in:
Deven Bansod 2018-03-24 13:38:11 +05:30
parent 21309cc8d4
commit 8b57a3e3b9
33 changed files with 596 additions and 848 deletions

View File

@ -1,12 +1,11 @@
import annotateAsPure from "../"; import annotateAsPure from "../";
import assert from "assert";
describe("@babel/helper-annotate-as-pure", () => { describe("@babel/helper-annotate-as-pure", () => {
it("will add leading comment", () => { it("will add leading comment", () => {
const node = {}; const node = {};
annotateAsPure(node); annotateAsPure(node);
assert.deepEqual(node.leadingComments, [ expect(node.leadingComments).toEqual([
{ {
type: "CommentBlock", type: "CommentBlock",
value: "#__PURE__", value: "#__PURE__",
@ -26,7 +25,7 @@ describe("@babel/helper-annotate-as-pure", () => {
annotateAsPure(node); annotateAsPure(node);
assert.deepEqual(node.leadingComments, [ expect(node.leadingComments).toEqual([
{ {
type: "CommentBlock", type: "CommentBlock",
value: "#__PURE__", value: "#__PURE__",

View File

@ -1,4 +1,3 @@
import chai from "chai";
import * as babel from "@babel/core"; import * as babel from "@babel/core";
import { ImportInjector } from "../"; import { ImportInjector } from "../";
@ -33,9 +32,9 @@ function test(sourceType, opts, initializer, expectedCode) {
], ],
}); });
chai expect(result.code.replace(/\s+/g, " ").trim()).toBe(
.expect(result.code.replace(/\s+/g, " ").trim()) (expectedCode || "").replace(/\s+/g, " ").trim(),
.to.equal((expectedCode || "").replace(/\s+/g, " ").trim()); );
} }
const testScript = test.bind(undefined, "script"); const testScript = test.bind(undefined, "script");
const testModule = test.bind(undefined, "module"); const testModule = test.bind(undefined, "module");
@ -90,11 +89,9 @@ describe("@babel/helper-module-imports", () => {
describe("using a CommonJS loader", () => { describe("using a CommonJS loader", () => {
it("should import", () => { it("should import", () => {
chai expect(() => {
.expect(() => {
testScript({ importedType }, addNamespace()); testScript({ importedType }, addNamespace());
}) }).toThrow("Cannot import an ES6 module from CommonJS");
.to.throw(Error, "Cannot import an ES6 module from CommonJS");
}); });
}); });
}); });
@ -302,11 +299,9 @@ describe("@babel/helper-module-imports", () => {
describe("using a CommonJS loader", () => { describe("using a CommonJS loader", () => {
it("should import", () => { it("should import", () => {
chai expect(() => {
.expect(() => {
testScript({ importedType }, addDefault()); testScript({ importedType }, addDefault());
}) }).toThrow("Cannot import an ES6 module from CommonJS");
.to.throw(Error, "Cannot import an ES6 module from CommonJS");
}); });
}); });
}); });
@ -390,14 +385,12 @@ describe("@babel/helper-module-imports", () => {
}); });
it("should fail to import with force-enabled liveness", () => { it("should fail to import with force-enabled liveness", () => {
chai expect(() => {
.expect(() => {
testScript( testScript(
{ importedInterop, ensureLiveReference: true }, { importedInterop, ensureLiveReference: true },
addDefault(), addDefault(),
); );
}) }).toThrow("No live reference for commonjs default");
.to.throw(Error, "No live reference for commonjs default");
}); });
}); });
}); });
@ -659,11 +652,9 @@ describe("@babel/helper-module-imports", () => {
describe("using a CommonJS loader", () => { describe("using a CommonJS loader", () => {
it("should import", () => { it("should import", () => {
chai expect(() => {
.expect(() => {
testScript({ importedType }, addNamed()); testScript({ importedType }, addNamed());
}) }).toThrow("Cannot import an ES6 module from CommonJS");
.to.throw(Error, "Cannot import an ES6 module from CommonJS");
}); });
}); });
}); });
@ -967,11 +958,9 @@ describe("@babel/helper-module-imports", () => {
describe("using a CommonJS loader", () => { describe("using a CommonJS loader", () => {
it("should import", () => { it("should import", () => {
chai expect(() => {
.expect(() => {
testScript({ importedType }, addSideEffect()); testScript({ importedType }, addSideEffect());
}) }).toThrow("Cannot import an ES6 module from CommonJS");
.to.throw(Error, "Cannot import an ES6 module from CommonJS");
}); });
}); });
}); });

View File

@ -1,4 +1,3 @@
import assert from "assert";
import { runCodeInTestContext } from ".."; import { runCodeInTestContext } from "..";
describe("helper-transform-fixture-test-runner", function() { describe("helper-transform-fixture-test-runner", function() {
@ -6,13 +5,13 @@ describe("helper-transform-fixture-test-runner", function() {
try { try {
global.foo = "outer"; global.foo = "outer";
runCodeInTestContext(` runCodeInTestContext(`
assert.equal(global.foo, undefined); expect(global.foo).toBeUndefined();
global.foo = "inner"; global.foo = "inner";
`); `);
assert.equal(global.foo, "outer"); expect(global.foo).toBe("outer");
runCodeInTestContext(` runCodeInTestContext(`
assert.equal(global.foo, "inner"); expect(global.foo).toBe("inner");
`); `);
} finally { } finally {
delete global.foo; delete global.foo;

View File

@ -1,4 +1,3 @@
import assert from "assert";
import chalk from "chalk"; import chalk from "chalk";
import stripAnsi from "strip-ansi"; import stripAnsi from "strip-ansi";
import highlight, { shouldHighlight, getChalk } from ".."; import highlight, { shouldHighlight, getChalk } from "..";
@ -24,8 +23,8 @@ describe("@babel/highlight", function() {
const code = "console.log('hi')"; const code = "console.log('hi')";
const result = highlight(code); const result = highlight(code);
const stripped = stripAnsi(result); const stripped = stripAnsi(result);
assert.ok(result.length > stripped.length); expect(result.length).toBeGreaterThan(stripped.length);
assert.equal(stripped, code); expect(stripped).toBe(code);
}); });
}); });
@ -36,8 +35,8 @@ describe("@babel/highlight", function() {
const code = "console.log('hi')"; const code = "console.log('hi')";
const result = highlight(code); const result = highlight(code);
const stripped = stripAnsi(result); const stripped = stripAnsi(result);
assert.ok(result.length === stripped.length); expect(result.length).toBe(stripped.length);
assert.equal(result, code); expect(result).toBe(code);
}); });
describe("and the forceColor option is passed", function() { describe("and the forceColor option is passed", function() {
@ -45,8 +44,8 @@ describe("@babel/highlight", function() {
const code = "console.log('hi')"; const code = "console.log('hi')";
const result = highlight(code, { forceColor: true }); const result = highlight(code, { forceColor: true });
const stripped = stripAnsi(result); const stripped = stripAnsi(result);
assert.ok(result.length > stripped.length); expect(result.length).toBeGreaterThan(stripped.length);
assert.equal(stripped, code); expect(stripped).toBe(code);
}); });
}); });
}); });
@ -57,7 +56,7 @@ describe("@babel/highlight", function() {
stubColorSupport(true); stubColorSupport(true);
it("returns true", function() { it("returns true", function() {
assert.ok(shouldHighlight({})); expect(shouldHighlight({})).toBeTruthy();
}); });
}); });
@ -65,12 +64,12 @@ describe("@babel/highlight", function() {
stubColorSupport(false); stubColorSupport(false);
it("returns false", function() { it("returns false", function() {
assert.ok(!shouldHighlight({})); expect(shouldHighlight({})).toBeFalsy();
}); });
describe("and the forceColor option is passed", function() { describe("and the forceColor option is passed", function() {
it("returns true", function() { it("returns true", function() {
assert.ok(shouldHighlight({ forceColor: true })); expect(shouldHighlight({ forceColor: true })).toBeTruthy();
}); });
}); });
}); });
@ -82,14 +81,13 @@ describe("@babel/highlight", function() {
describe("when forceColor is not passed", function() { describe("when forceColor is not passed", function() {
it("returns a Chalk instance", function() { it("returns a Chalk instance", function() {
assert.equal(getChalk({}).constructor, chalk.constructor); expect(getChalk({}).constructor).toBe(chalk.constructor);
}); });
}); });
describe("when forceColor is passed", function() { describe("when forceColor is passed", function() {
it("returns a Chalk instance", function() { it("returns a Chalk instance", function() {
assert.equal( expect(getChalk({ forceColor: true }).constructor).toBe(
getChalk({ forceColor: true }).constructor,
chalk.constructor, chalk.constructor,
); );
}); });
@ -101,14 +99,13 @@ describe("@babel/highlight", function() {
describe("when forceColor is not passed", function() { describe("when forceColor is not passed", function() {
it("returns a Chalk instance", function() { it("returns a Chalk instance", function() {
assert.equal(getChalk({}).constructor, chalk.constructor); expect(getChalk({}).constructor).toBe(chalk.constructor);
}); });
}); });
describe("when forceColor is passed", function() { describe("when forceColor is passed", function() {
it("returns a Chalk instance", function() { it("returns a Chalk instance", function() {
assert.equal( expect(getChalk({ forceColor: true }).constructor).toBe(
getChalk({ forceColor: true }).constructor,
chalk.constructor, chalk.constructor,
); );
}); });

View File

@ -1,13 +1,11 @@
const includes = require("lodash/includes"); const includes = require("lodash/includes");
const readdir = require("fs-readdir-recursive"); const readdir = require("fs-readdir-recursive");
const helper = require("@babel/helper-fixtures"); const helper = require("@babel/helper-fixtures");
const assert = require("assert");
const rimraf = require("rimraf"); const rimraf = require("rimraf");
const outputFileSync = require("output-file-sync"); const outputFileSync = require("output-file-sync");
const child = require("child_process"); const child = require("child_process");
const merge = require("lodash/merge"); const merge = require("lodash/merge");
const path = require("path"); const path = require("path");
const chai = require("chai");
const fs = require("fs"); const fs = require("fs");
const fixtureLoc = path.join(__dirname, "fixtures"); const fixtureLoc = path.join(__dirname, "fixtures");
@ -53,15 +51,9 @@ const assertTest = function(stdout, stderr, opts) {
if (opts.stderr) { if (opts.stderr) {
if (opts.stderrContains) { if (opts.stderrContains) {
assert.ok( expect(includes(stderr, expectStderr)).toBeTruthy();
includes(stderr, expectStderr),
"stderr " +
JSON.stringify(stderr) +
" didn't contain " +
JSON.stringify(expectStderr),
);
} else { } else {
chai.expect(stderr).to.equal(expectStderr, "stderr didn't match"); expect(stderr).toBe(expectStderr);
} }
} else if (stderr) { } else if (stderr) {
throw new Error("stderr:\n" + stderr); throw new Error("stderr:\n" + stderr);
@ -73,15 +65,9 @@ const assertTest = function(stdout, stderr, opts) {
if (opts.stdout) { if (opts.stdout) {
if (opts.stdoutContains) { if (opts.stdoutContains) {
assert.ok( expect(includes(stdout, expectStdout)).toBeTruthy();
includes(stdout, expectStdout),
"stdout " +
JSON.stringify(stdout) +
" didn't contain " +
JSON.stringify(expectStdout),
);
} else { } else {
chai.expect(stdout).to.equal(expectStdout, "stdout didn't match"); expect(stdout).toBe(expectStdout);
} }
} else if (stdout) { } else if (stdout) {
throw new Error("stdout:\n" + stdout); throw new Error("stdout:\n" + stdout);
@ -92,24 +78,19 @@ const assertTest = function(stdout, stderr, opts) {
Object.keys(actualFiles).forEach(function(filename) { Object.keys(actualFiles).forEach(function(filename) {
if (!opts.inFiles.hasOwnProperty(filename)) { if (!opts.inFiles.hasOwnProperty(filename)) {
const expect = opts.outFiles[filename]; const expected = opts.outFiles[filename];
const actual = actualFiles[filename]; const actual = actualFiles[filename];
chai.expect(expect, "Output is missing: " + filename).to.not.be expect(expected).not.toBeUndefined();
.undefined;
if (expect) { if (expected) {
chai expect(actual).toBe(expected);
.expect(actual)
.to.equal(expect, "Compiled output does not match: " + filename);
} }
} }
}); });
Object.keys(opts.outFiles).forEach(function(filename) { Object.keys(opts.outFiles).forEach(function(filename) {
chai expect(actualFiles).toHaveProperty(filename);
.expect(actualFiles, "Extraneous file in output: " + filename)
.to.contain.key(filename);
}); });
} }
}; };

View File

@ -1,4 +1,3 @@
const assert = require("assert");
const babel = require("@babel/core"); const babel = require("@babel/core");
test("Doesn't use the same object for two different nodes in the AST", function() { test("Doesn't use the same object for two different nodes in the AST", function() {
@ -9,26 +8,20 @@ test("Doesn't use the same object for two different nodes in the AST", function(
plugins: [[require("../"), { loose: true }]], plugins: [[require("../"), { loose: true }]],
}).ast; }).ast;
assert.equal(ast.program.body[0].declarations[0].id.type, "Identifier"); expect(ast.program.body[0].declarations[0].id.type).toBe("Identifier");
assert.equal(ast.program.body[2].expression.type, "MemberExpression"); expect(ast.program.body[2].expression.type).toBe("MemberExpression");
assert.equal(ast.program.body[2].expression.object.type, "Identifier"); expect(ast.program.body[2].expression.object.type).toBe("Identifier");
assert.equal(ast.program.body[3].expression.type, "MemberExpression"); expect(ast.program.body[3].expression.type).toBe("MemberExpression");
assert.equal(ast.program.body[3].expression.object.type, "Identifier"); expect(ast.program.body[3].expression.object.type).toBe("Identifier");
assert.notStrictEqual( expect(ast.program.body[2].expression.object).not.toBe(
ast.program.body[2].expression.object,
ast.program.body[3].expression.object, ast.program.body[3].expression.object,
"Expected different nodes in the AST to not be the same object (one)",
); );
assert.notStrictEqual( expect(ast.program.body[0].declarations[0].id).not.toBe(
ast.program.body[0].declarations[0].id,
ast.program.body[3].expression.object, ast.program.body[3].expression.object,
"Expected different nodes in the AST to not be the same object (two)",
); );
assert.notStrictEqual( expect(ast.program.body[0].declarations[0].id).not.toBe(
ast.program.body[0].declarations[0].id,
ast.program.body[2].expression.object, ast.program.body[2].expression.object,
"Expected different nodes in the AST to not be the same object (three)",
); );
}); });

View File

@ -1,4 +1,3 @@
const assert = require("assert");
const babel = require("@babel/core"); const babel = require("@babel/core");
const vm = require("vm"); const vm = require("vm");
@ -27,9 +26,5 @@ test("Re-export doesn't overwrite __esModule flag", function() {
vm.runInNewContext(code, context); vm.runInNewContext(code, context);
// exports.__esModule shouldn't be overwritten. // exports.__esModule shouldn't be overwritten.
assert.equal( expect(context.exports.__esModule).toBe(true);
context.exports.__esModule,
true,
"Expected exports.__esModule === true",
);
}); });

View File

@ -1,5 +1,3 @@
const assert = require("assert");
(process.env.TEST_TYPE === "cov" ? describe.skip : describe)( (process.env.TEST_TYPE === "cov" ? describe.skip : describe)(
"babel-preset-env-standalone", "babel-preset-env-standalone",
() => { () => {
@ -14,7 +12,7 @@ const assert = require("assert");
sourceType: "script", sourceType: "script",
presets: ["env"], presets: ["env"],
}).code; }).code;
assert.equal(output, "var a = 1;"); expect(output).toBe("var a = 1;");
}); });
it("doesn't transpile `const` with chrome 60", () => { it("doesn't transpile `const` with chrome 60", () => {
@ -31,7 +29,7 @@ const assert = require("assert");
], ],
], ],
}).code; }).code;
assert.equal(output, "const a = 1;"); expect(output).toBe("const a = 1;");
}); });
it("transpiles `const` with chrome 60 and preset-es2015", () => { it("transpiles `const` with chrome 60 and preset-es2015", () => {
@ -49,7 +47,7 @@ const assert = require("assert");
"es2015", "es2015",
], ],
}).code; }).code;
assert.equal(output, "var a = 1;"); expect(output).toBe("var a = 1;");
}); });
it("uses transform-new-targets plugin", () => { it("uses transform-new-targets plugin", () => {
@ -57,8 +55,7 @@ const assert = require("assert");
sourceType: "script", sourceType: "script",
presets: ["env"], presets: ["env"],
}).code; }).code;
assert.equal( expect(output).toBe(
output,
"function Foo() {\n this instanceof Foo ? this.constructor : void 0;\n}", "function Foo() {\n this instanceof Foo ? this.constructor : void 0;\n}",
); );
}); });

View File

@ -1,4 +1,3 @@
const chai = require("chai");
const child = require("child_process"); const child = require("child_process");
const fs = require("fs-extra"); const fs = require("fs-extra");
const helper = require("@babel/helper-fixtures"); const helper = require("@babel/helper-fixtures");
@ -28,7 +27,7 @@ const testOutputType = (type, stdTarg, opts) => {
if (optsTarg) { if (optsTarg) {
const expectStdout = optsTarg.trim(); const expectStdout = optsTarg.trim();
chai.expect(stdTarg).to.equal(expectStdout, `${type} didn't match`); expect(stdTarg).toBe(expectStdout);
} else { } else {
const file = path.join(opts.testLoc, `${type}.txt`); const file = path.join(opts.testLoc, `${type}.txt`);
console.log(`New test file created: ${file}`); console.log(`New test file created: ${file}`);

View File

@ -1,7 +1,6 @@
"use strict"; "use strict";
const defaults = require("../lib/defaults.js"); const defaults = require("../lib/defaults.js");
const assert = require("assert");
const { const {
getPlatformSpecificDefaultFor, getPlatformSpecificDefaultFor,
@ -15,7 +14,7 @@ describe("defaults", () => {
chrome: "63", chrome: "63",
node: "8", node: "8",
}); });
assert.deepEqual(defaultWebIncludesForChromeAndNode, [ expect(defaultWebIncludesForChromeAndNode).toEqual([
"web.timers", "web.timers",
"web.immediate", "web.immediate",
"web.dom.iterable", "web.dom.iterable",
@ -26,7 +25,7 @@ describe("defaults", () => {
const defaultWebIncludesForChromeAndNode = getPlatformSpecificDefaultFor({ const defaultWebIncludesForChromeAndNode = getPlatformSpecificDefaultFor({
node: "8", node: "8",
}); });
assert.equal(defaultWebIncludesForChromeAndNode, null); expect(defaultWebIncludesForChromeAndNode).toBeNull();
}); });
}); });
@ -35,7 +34,7 @@ describe("defaults", () => {
const defaultWebIncludesForChromeAndNode = getOptionSpecificExcludesFor({ const defaultWebIncludesForChromeAndNode = getOptionSpecificExcludesFor({
loose: true, loose: true,
}); });
assert.deepEqual(defaultWebIncludesForChromeAndNode, [ expect(defaultWebIncludesForChromeAndNode).toEqual([
"transform-typeof-symbol", "transform-typeof-symbol",
]); ]);
}); });
@ -44,7 +43,7 @@ describe("defaults", () => {
const defaultWebIncludesForChromeAndNode = getOptionSpecificExcludesFor({ const defaultWebIncludesForChromeAndNode = getOptionSpecificExcludesFor({
loose: false, loose: false,
}); });
assert.deepEqual(defaultWebIncludesForChromeAndNode, null); expect(defaultWebIncludesForChromeAndNode).toBeNull();
}); });
}); });
}); });

View File

@ -1,14 +1,13 @@
"use strict"; "use strict";
const babelPresetEnv = require("../lib/index.js"); const babelPresetEnv = require("../lib/index.js");
const assert = require("assert");
describe("babel-preset-env", () => { describe("babel-preset-env", () => {
describe("isPluginRequired", () => { describe("isPluginRequired", () => {
const MAX_VERSION = `${Number.MAX_SAFE_INTEGER}.0.0`; const MAX_VERSION = `${Number.MAX_SAFE_INTEGER}.0.0`;
it("returns true if no targets are specified", () => { it("returns true if no targets are specified", () => {
assert.strictEqual(babelPresetEnv.isPluginRequired({}, {}), true); expect(babelPresetEnv.isPluginRequired({}, {})).toBe(true);
}); });
it("returns true if plugin feature is not implemented in one or more targets", () => { it("returns true if plugin feature is not implemented in one or more targets", () => {
@ -23,18 +22,12 @@ describe("babel-preset-env", () => {
chrome: MAX_VERSION, chrome: MAX_VERSION,
firefox: MAX_VERSION, firefox: MAX_VERSION,
}; };
assert.strictEqual( expect(babelPresetEnv.isPluginRequired(targets, plugin)).toBe(false);
babelPresetEnv.isPluginRequired(targets, plugin),
false,
);
targets = { targets = {
edge: "12", edge: "12",
}; };
assert.strictEqual( expect(babelPresetEnv.isPluginRequired(targets, plugin)).toBe(true);
babelPresetEnv.isPluginRequired(targets, plugin),
true,
);
}); });
it("returns false if plugin feature is implemented by lower than target", () => { it("returns false if plugin feature is implemented by lower than target", () => {
@ -45,10 +38,7 @@ describe("babel-preset-env", () => {
chrome: MAX_VERSION, chrome: MAX_VERSION,
}; };
assert.strictEqual( expect(babelPresetEnv.isPluginRequired(targets, plugin)).toBe(false);
babelPresetEnv.isPluginRequired(targets, plugin),
false,
);
}); });
it("returns false if plugin feature is implemented is equal to target", () => { it("returns false if plugin feature is implemented is equal to target", () => {
@ -58,10 +48,7 @@ describe("babel-preset-env", () => {
const targets = { const targets = {
chrome: "49.0.0", chrome: "49.0.0",
}; };
assert.strictEqual( expect(babelPresetEnv.isPluginRequired(targets, plugin)).toBe(false);
babelPresetEnv.isPluginRequired(targets, plugin),
false,
);
}); });
it("returns true if plugin feature is implemented is greater than target", () => { it("returns true if plugin feature is implemented is greater than target", () => {
@ -71,10 +58,7 @@ describe("babel-preset-env", () => {
const targets = { const targets = {
chrome: "49.0.0", chrome: "49.0.0",
}; };
assert.strictEqual( expect(babelPresetEnv.isPluginRequired(targets, plugin)).toBe(true);
babelPresetEnv.isPluginRequired(targets, plugin),
true,
);
}); });
it("returns when target is a decimal", () => { it("returns when target is a decimal", () => {
@ -84,10 +68,7 @@ describe("babel-preset-env", () => {
const targets = { const targets = {
node: "6.10.0", node: "6.10.0",
}; };
assert.strictEqual( expect(babelPresetEnv.isPluginRequired(targets, plugin)).toBe(false);
babelPresetEnv.isPluginRequired(targets, plugin),
false,
);
}); });
it("throws an error if target version is invalid", () => { it("throws an error if target version is invalid", () => {
@ -97,33 +78,29 @@ describe("babel-preset-env", () => {
const targets = { const targets = {
chrome: 55, chrome: 55,
}; };
assert.throws(() => babelPresetEnv.isPluginRequired(targets, plugin)); expect(() => babelPresetEnv.isPluginRequired(targets, plugin)).toThrow();
}); });
}); });
describe("transformIncludesAndExcludes", () => { describe("transformIncludesAndExcludes", () => {
it("should return in transforms array", () => { it("should return in transforms array", () => {
assert.deepEqual( expect(
babelPresetEnv.transformIncludesAndExcludes([ babelPresetEnv.transformIncludesAndExcludes([
"transform-arrow-functions", "transform-arrow-functions",
]), ]),
{ ).toEqual({
all: ["transform-arrow-functions"], all: ["transform-arrow-functions"],
plugins: new Set(["transform-arrow-functions"]), plugins: new Set(["transform-arrow-functions"]),
builtIns: new Set(), builtIns: new Set(),
}, });
);
}); });
it("should return in built-ins array", () => { it("should return in built-ins array", () => {
assert.deepEqual( expect(babelPresetEnv.transformIncludesAndExcludes(["es6.map"])).toEqual({
babelPresetEnv.transformIncludesAndExcludes(["es6.map"]),
{
all: ["es6.map"], all: ["es6.map"],
plugins: new Set(), plugins: new Set(),
builtIns: new Set(["es6.map"]), builtIns: new Set(["es6.map"]),
}, });
);
}); });
}); });
}); });

View File

@ -1,7 +1,6 @@
"use strict"; "use strict";
const normalizeOptions = require("../lib/normalize-options.js"); const normalizeOptions = require("../lib/normalize-options.js");
const assert = require("assert");
const { const {
checkDuplicateIncludeExcludes, checkDuplicateIncludeExcludes,
@ -15,7 +14,7 @@ describe("normalize-options", () => {
const normalized = normalizeOptions.default({ const normalized = normalizeOptions.default({
include: ["babel-plugin-transform-spread", "transform-classes"], include: ["babel-plugin-transform-spread", "transform-classes"],
}); });
assert.deepEqual(normalized.include, [ expect(normalized.include).toEqual([
"transform-spread", "transform-spread",
"transform-classes", "transform-classes",
]); ]);
@ -23,7 +22,7 @@ describe("normalize-options", () => {
it("should not normalize babel-plugin with prefix", () => { it("should not normalize babel-plugin with prefix", () => {
const normalized = normalizePluginName("prefix-babel-plugin-postfix"); const normalized = normalizePluginName("prefix-babel-plugin-postfix");
assert.equal(normalized, "prefix-babel-plugin-postfix"); expect(normalized).toBe("prefix-babel-plugin-postfix");
}); });
it("should throw if duplicate names in `include` and `exclude`", () => { it("should throw if duplicate names in `include` and `exclude`", () => {
@ -33,7 +32,7 @@ describe("normalize-options", () => {
exclude: ["transform-spread"], exclude: ["transform-spread"],
}); });
}; };
assert.throws(normalizeWithSameIncludes, Error); expect(normalizeWithSameIncludes).toThrow();
}); });
}); });
@ -44,14 +43,14 @@ describe("normalize-options", () => {
include: ["non-existing-plugin"], include: ["non-existing-plugin"],
}); });
}; };
assert.throws(normalizeWithNonExistingPlugin, Error); expect(normalizeWithNonExistingPlugin).toThrow(Error);
}); });
it("should expand regular expressions in `include` and `exclude`", () => { it("should expand regular expressions in `include` and `exclude`", () => {
const normalized = normalizeOptions.default({ const normalized = normalizeOptions.default({
include: ["^[a-z]*-spread", "babel-plugin-transform-classes"], include: ["^[a-z]*-spread", "babel-plugin-transform-classes"],
}); });
assert.deepEqual(normalized.include, [ expect(normalized.include).toEqual([
"transform-spread", "transform-spread",
"transform-classes", "transform-classes",
]); ]);
@ -61,7 +60,7 @@ describe("normalize-options", () => {
const normalized = normalizeOptions.default({ const normalized = normalizeOptions.default({
exclude: ["es6.math.log.*"], exclude: ["es6.math.log.*"],
}); });
assert.deepEqual(normalized.exclude, [ expect(normalized.exclude).toEqual([
"es6.math.log1p", "es6.math.log1p",
"es6.math.log10", "es6.math.log10",
"es6.math.log2", "es6.math.log2",
@ -75,7 +74,7 @@ describe("normalize-options", () => {
exclude: ["es6.math.log.*"], exclude: ["es6.math.log.*"],
}); });
}; };
assert.throws(normalizeWithNonExistingPlugin, Error); expect(normalizeWithNonExistingPlugin).toThrow(Error);
}); });
it("should not do partial match if not explicitly defined `include` and `exclude`", () => { it("should not do partial match if not explicitly defined `include` and `exclude`", () => {
@ -83,83 +82,83 @@ describe("normalize-options", () => {
include: ["es6.reflect.set-prototype-of"], include: ["es6.reflect.set-prototype-of"],
exclude: ["es6.reflect.set"], exclude: ["es6.reflect.set"],
}); });
assert.deepEqual(normalized.include, ["es6.reflect.set-prototype-of"]); expect(normalized.include).toEqual(["es6.reflect.set-prototype-of"]);
assert.deepEqual(normalized.exclude, ["es6.reflect.set"]); expect(normalized.exclude).toEqual(["es6.reflect.set"]);
}); });
}); });
describe("validateBoolOption", () => { describe("validateBoolOption", () => {
it("`undefined` option returns false", () => { it("`undefined` option returns false", () => {
assert(validateBoolOption("test", undefined, false) === false); expect(validateBoolOption("test", undefined, false)).toBe(false);
}); });
it("`false` option returns false", () => { it("`false` option returns false", () => {
assert(validateBoolOption("test", false, false) === false); expect(validateBoolOption("test", false, false)).toBe(false);
}); });
it("`true` option returns true", () => { it("`true` option returns true", () => {
assert(validateBoolOption("test", true, false) === true); expect(validateBoolOption("test", true, false)).toBe(true);
}); });
it("array option is invalid", () => { it("array option is invalid", () => {
assert.throws(() => { expect(() => {
validateBoolOption("test", [], false); validateBoolOption("test", [], false);
}); }).toThrow();
}); });
}); });
describe("checkDuplicateIncludeExcludes", function() { describe("checkDuplicateIncludeExcludes", function() {
it("should throw if duplicate names in both", function() { it("should throw if duplicate names in both", function() {
assert.throws(() => { expect(() => {
checkDuplicateIncludeExcludes( checkDuplicateIncludeExcludes(
["transform-regenerator", "map"], ["transform-regenerator", "map"],
["transform-regenerator", "map"], ["transform-regenerator", "map"],
); );
}, Error); }).toThrow();
}); });
it("should not throw if no duplicate names in both", function() { it("should not throw if no duplicate names in both", function() {
assert.doesNotThrow(() => { expect(() => {
checkDuplicateIncludeExcludes(["transform-regenerator"], ["map"]); checkDuplicateIncludeExcludes(["transform-regenerator"], ["map"]);
}, Error); }).not.toThrow();
}); });
}); });
describe("validateModulesOption", () => { describe("validateModulesOption", () => {
it("`undefined` option returns commonjs", () => { it("`undefined` option returns commonjs", () => {
assert(validateModulesOption() === "commonjs"); expect(validateModulesOption()).toBe("commonjs");
}); });
it("`false` option returns commonjs", () => { it("`false` option returns commonjs", () => {
assert(validateModulesOption(false) === false); expect(validateModulesOption(false)).toBe(false);
}); });
it("commonjs option is valid", () => { it("commonjs option is valid", () => {
assert(validateModulesOption("commonjs") === "commonjs"); expect(validateModulesOption()).toBe("commonjs");
}); });
it("systemjs option is valid", () => { it("systemjs option is valid", () => {
assert(validateModulesOption("systemjs") === "systemjs"); expect(validateModulesOption("systemjs")).toBe("systemjs");
}); });
it("amd option is valid", () => { it("amd option is valid", () => {
assert(validateModulesOption("amd") === "amd"); expect(validateModulesOption("amd")).toBe("amd");
}); });
it("umd option is valid", () => { it("umd option is valid", () => {
assert(validateModulesOption("umd") === "umd"); expect(validateModulesOption("umd")).toBe("umd");
}); });
it("`true` option is invalid", () => { it("`true` option is invalid", () => {
assert.throws(() => { expect(() => {
validateModulesOption(true); validateModulesOption(true);
}, Error); }).toThrow();
}); });
it("array option is invalid", () => { it("array option is invalid", () => {
assert.throws(() => { expect(() => {
assert(validateModulesOption([])); validateModulesOption([]);
}, Error); }).toThrow();
}); });
}); });
}); });

View File

@ -1,9 +1,8 @@
import assert from "assert";
import getTargets from "../lib/targets-parser"; import getTargets from "../lib/targets-parser";
describe("getTargets", () => { describe("getTargets", () => {
it("parses", () => { it("parses", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
chrome: 49, chrome: 49,
firefox: "55", firefox: "55",
@ -11,166 +10,155 @@ describe("getTargets", () => {
node: "6.10", node: "6.10",
electron: "1.6", electron: "1.6",
}), }),
{ ).toEqual({
chrome: "49.0.0", chrome: "49.0.0",
electron: "1.6.0", electron: "1.6.0",
firefox: "55.0.0", firefox: "55.0.0",
ie: "9.0.0", ie: "9.0.0",
node: "6.10.0", node: "6.10.0",
}, });
);
}); });
describe("browser", () => { describe("browser", () => {
it("merges browser key targets", () => { it("merges browser key targets", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
browsers: "chrome 56, ie 11, firefox 51, safari 9", browsers: "chrome 56, ie 11, firefox 51, safari 9",
chrome: "49", chrome: "49",
firefox: "55", firefox: "55",
ie: "9", ie: "9",
}), }),
{ ).toEqual({
chrome: "49.0.0", chrome: "49.0.0",
firefox: "55.0.0", firefox: "55.0.0",
ie: "9.0.0", ie: "9.0.0",
safari: "9.0.0", safari: "9.0.0",
}, });
);
}); });
it("works with TP versions", () => { it("works with TP versions", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
browsers: "safari tp", browsers: "safari tp",
}), }),
{ ).toEqual({
safari: "tp", safari: "tp",
}, });
);
}); });
it("returns TP version in lower case", () => { it("returns TP version in lower case", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
safari: "TP", safari: "TP",
}), }),
{ ).toEqual({
safari: "tp", safari: "tp",
}, });
);
}); });
it("ignores invalid", () => { it("ignores invalid", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
browsers: 59, browsers: 59,
chrome: "49", chrome: "49",
firefox: "55", firefox: "55",
ie: "11", ie: "11",
}), }),
{ ).toEqual({
chrome: "49.0.0", chrome: "49.0.0",
firefox: "55.0.0", firefox: "55.0.0",
ie: "11.0.0", ie: "11.0.0",
}, });
);
}); });
}); });
describe("esmodules", () => { describe("esmodules", () => {
it("returns browsers supporting modules", () => { it("returns browsers supporting modules", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
esmodules: true, esmodules: true,
}), }),
{ ).toEqual({
chrome: "61.0.0", chrome: "61.0.0",
safari: "10.1.0", safari: "10.1.0",
firefox: "60.0.0", firefox: "60.0.0",
ios: "10.3.0", ios: "10.3.0",
edge: "16.0.0", edge: "16.0.0",
}, });
);
}); });
it("returns browsers supporting modules, ignoring browsers key", () => { it("returns browsers supporting modules, ignoring browsers key", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
esmodules: true, esmodules: true,
browsers: "ie 8", browsers: "ie 8",
}), }),
{ ).toEqual({
chrome: "61.0.0", chrome: "61.0.0",
safari: "10.1.0", safari: "10.1.0",
firefox: "60.0.0", firefox: "60.0.0",
ios: "10.3.0", ios: "10.3.0",
edge: "16.0.0", edge: "16.0.0",
}, });
);
}); });
it("returns browser supporting modules and keyed browser overrides", () => { it("returns browser supporting modules and keyed browser overrides", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
esmodules: true, esmodules: true,
ie: 11, ie: 11,
}), }),
{ ).toEqual({
chrome: "61.0.0", chrome: "61.0.0",
safari: "10.1.0", safari: "10.1.0",
firefox: "60.0.0", firefox: "60.0.0",
ios: "10.3.0", ios: "10.3.0",
ie: "11.0.0", ie: "11.0.0",
edge: "16.0.0", edge: "16.0.0",
}, });
);
}); });
it("returns browser supporting modules and keyed browser overrides, ignoring browsers field", () => { it("returns browser supporting modules and keyed browser overrides, ignoring browsers field", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
esmodules: true, esmodules: true,
browsers: "ie 10", browsers: "ie 10",
ie: 11, ie: 11,
}), }),
{ ).toEqual({
chrome: "61.0.0", chrome: "61.0.0",
safari: "10.1.0", safari: "10.1.0",
ios: "10.3.0", ios: "10.3.0",
ie: "11.0.0", ie: "11.0.0",
edge: "16.0.0", edge: "16.0.0",
firefox: "60.0.0", firefox: "60.0.0",
}, });
);
}); });
}); });
describe("node", () => { describe("node", () => {
it("should return the current node version with option 'current'", () => { it("should return the current node version with option 'current'", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
node: true, node: true,
}), }),
{ ).toEqual({
node: process.versions.node, node: process.versions.node,
}, });
);
}); });
}); });
describe("electron", () => { describe("electron", () => {
it("should be its own target", () => { it("should be its own target", () => {
assert.deepEqual( expect(
getTargets({ getTargets({
chrome: "46", chrome: "46",
electron: "0.34", electron: "0.34",
}), }),
{ ).toEqual({
chrome: "46.0.0", chrome: "46.0.0",
electron: "0.34.0", electron: "0.34.0",
}, });
);
}); });
}); });
}); });

View File

@ -1,48 +1,46 @@
"use strict"; "use strict";
const utils = require("../lib/utils"); const utils = require("../lib/utils");
const assert = require("assert");
const { prettifyTargets, prettifyVersion, semverify } = utils; const { prettifyTargets, prettifyVersion, semverify } = utils;
describe("utils", () => { describe("utils", () => {
describe("semverify", () => { describe("semverify", () => {
it("returns", () => { it("returns", () => {
assert.strictEqual(semverify("1"), "1.0.0"); expect(semverify("1")).toBe("1.0.0");
assert.strictEqual(semverify("1.0"), "1.0.0"); expect(semverify("1.0")).toBe("1.0.0");
assert.strictEqual(semverify("1.0.0"), "1.0.0"); expect(semverify("1.0.0")).toBe("1.0.0");
assert.strictEqual(semverify(1), "1.0.0"); expect(semverify(1)).toBe("1.0.0");
assert.strictEqual(semverify(1.2), "1.2.0"); expect(semverify(1.2)).toBe("1.2.0");
}); });
}); });
describe("prettifyVersion", () => { describe("prettifyVersion", () => {
it("returns", () => { it("returns", () => {
assert.strictEqual(prettifyVersion(true), true); expect(prettifyVersion(true)).toBe(true);
assert.strictEqual(prettifyVersion("0.16.0"), "0.16"); expect(prettifyVersion("0.16.0")).toBe("0.16");
assert.strictEqual(prettifyVersion("1.0.0"), "1"); expect(prettifyVersion("1.0.0")).toBe("1");
assert.strictEqual(prettifyVersion("1.1.0"), "1.1"); expect(prettifyVersion("1.1.0")).toBe("1.1");
assert.strictEqual(prettifyVersion("1.0.2"), "1.0.2"); expect(prettifyVersion("1.0.2")).toBe("1.0.2");
assert.strictEqual(prettifyVersion("1.2.3"), "1.2.3"); expect(prettifyVersion("1.2.3")).toBe("1.2.3");
}); });
}); });
describe("prettifyTargets", () => { describe("prettifyTargets", () => {
it("returns", () => { it("returns", () => {
assert.deepStrictEqual(prettifyTargets({}), {}); expect(prettifyTargets({})).toEqual({});
assert.deepStrictEqual( expect(
prettifyTargets({ prettifyTargets({
chrome: "54.0.0", chrome: "54.0.0",
electron: "1.6.0", electron: "1.6.0",
node: "0.12.0", node: "0.12.0",
}), }),
{ ).toEqual({
chrome: "54", chrome: "54",
electron: "1.6", electron: "1.6",
node: "0.12", node: "0.12",
}, });
);
}); });
}); });
}); });

View File

@ -1,12 +1,11 @@
import * as babel from "@babel/core"; import * as babel from "@babel/core";
import es2015 from "../lib"; import es2015 from "../lib";
import { expect } from "chai";
describe("es2015 preset", function() { describe("es2015 preset", function() {
it("does throw clear error when no options passed for Babel 6", () => { it("does throw clear error when no options passed for Babel 6", () => {
expect(function() { expect(function() {
es2015({ version: "6.5.0" }); es2015({ version: "6.5.0" });
}).to.throw(Error, /Requires Babel "\^7.0.0-0"/); }).toThrow(Error, /Requires Babel "\^7.0.0-0"/);
}); });
describe("options", function() { describe("options", function() {
@ -14,7 +13,7 @@ describe("es2015 preset", function() {
it("throws on non-boolean value", function() { it("throws on non-boolean value", function() {
expect(function() { expect(function() {
babel.transform("", { presets: [[es2015, { loose: 1 }]] }); babel.transform("", { presets: [[es2015, { loose: 1 }]] });
}).to.throw(/must be a boolean/); }).toThrow(/must be a boolean/);
}); });
}); });
@ -22,7 +21,7 @@ describe("es2015 preset", function() {
it("throws on non-boolean value", function() { it("throws on non-boolean value", function() {
expect(function() { expect(function() {
babel.transform("", { presets: [[es2015, { spec: 1 }]] }); babel.transform("", { presets: [[es2015, { spec: 1 }]] });
}).to.throw(/must be a boolean/); }).toThrow(/must be a boolean/);
}); });
}); });
@ -30,31 +29,31 @@ describe("es2015 preset", function() {
it("doesn't throw when passing one false", function() { it("doesn't throw when passing one false", function() {
expect(function() { expect(function() {
babel.transform("", { presets: [[es2015, { modules: false }]] }); babel.transform("", { presets: [[es2015, { modules: false }]] });
}).not.to.throw(); }).not.toThrow();
}); });
it("doesn't throw when passing one of: 'commonjs', 'amd', 'umd', 'systemjs", function() { it("doesn't throw when passing one of: 'commonjs', 'amd', 'umd', 'systemjs", function() {
expect(function() { expect(function() {
babel.transform("", { presets: [[es2015, { modules: "commonjs" }]] }); babel.transform("", { presets: [[es2015, { modules: "commonjs" }]] });
}).not.to.throw(); }).not.toThrow();
expect(function() { expect(function() {
babel.transform("", { presets: [[es2015, { modules: "amd" }]] }); babel.transform("", { presets: [[es2015, { modules: "amd" }]] });
}).not.to.throw(); }).not.toThrow();
expect(function() { expect(function() {
babel.transform("", { presets: [[es2015, { modules: "umd" }]] }); babel.transform("", { presets: [[es2015, { modules: "umd" }]] });
}).not.to.throw(); }).not.toThrow();
expect(function() { expect(function() {
babel.transform("", { presets: [[es2015, { modules: "systemjs" }]] }); babel.transform("", { presets: [[es2015, { modules: "systemjs" }]] });
}).not.to.throw(); }).not.toThrow();
}); });
it("throws when passing neither false nor one of: 'commonjs', 'amd', 'umd', 'systemjs'", function() { it("throws when passing neither false nor one of: 'commonjs', 'amd', 'umd', 'systemjs'", function() {
expect(function() { expect(function() {
babel.transform("", { presets: [[es2015, { modules: 1 }]] }); babel.transform("", { presets: [[es2015, { modules: 1 }]] });
}).to.throw(); }).toThrow();
}); });
}); });
}); });

View File

@ -1,10 +1,9 @@
import react from "../lib"; import react from "../lib";
import { expect } from "chai";
describe("react preset", () => { describe("react preset", () => {
it("does throw clear error when no options passed for Babel 6", () => { it("does throw clear error when no options passed for Babel 6", () => {
expect(() => { expect(() => {
react({ version: "6.5.0" }); react({ version: "6.5.0" });
}).to.throw(Error, /Requires Babel "\^7.0.0-0"/); }).toThrow(Error, /Requires Babel "\^7.0.0-0"/);
}); });
}); });

View File

@ -1,5 +1,3 @@
const assert = require("assert");
// Basic smoke tests for @babel/standalone // Basic smoke tests for @babel/standalone
(process.env.TEST_TYPE === "cov" ? describe.skip : describe)( (process.env.TEST_TYPE === "cov" ? describe.skip : describe)(
"@babel/standalone", "@babel/standalone",
@ -10,8 +8,7 @@ const assert = require("assert");
const output = Babel.transform('const getMessage = () => "Hello World"', { const output = Babel.transform('const getMessage = () => "Hello World"', {
presets: ["es2015-no-commonjs"], presets: ["es2015-no-commonjs"],
}).code; }).code;
assert.equal( expect(output).toBe(
output,
"var getMessage = function getMessage() {\n" + "var getMessage = function getMessage() {\n" +
' return "Hello World";\n' + ' return "Hello World";\n' +
"};", "};",
@ -22,19 +19,19 @@ const assert = require("assert");
sourceType: "script", sourceType: "script",
presets: ["es2015-loose"], presets: ["es2015-loose"],
}).code; }).code;
assert.equal(output, "var A = function A() {};"); expect(output).toBe("var A = function A() {};");
}); });
it("handles the typescript preset", () => { it("handles the typescript preset", () => {
const output = Babel.transform("var a: string;", { const output = Babel.transform("var a: string;", {
presets: ["typescript"], presets: ["typescript"],
}).code; }).code;
assert.equal(output, "var a;"); expect(output).toBe("var a;");
}); });
it("handles the flow preset", () => { it("handles the flow preset", () => {
const output = Babel.transform("var a: string;", { const output = Babel.transform("var a: string;", {
presets: ["flow"], presets: ["flow"],
}).code; }).code;
assert.equal(output, "var a;"); expect(output).toBe("var a;");
}); });
it("can translate simple ast", () => { it("can translate simple ast", () => {
const ast = { const ast = {
@ -60,7 +57,7 @@ const assert = require("assert");
}; };
const output = Babel.transformFromAst(ast, "42", { presets: ["es2015"] }) const output = Babel.transformFromAst(ast, "42", { presets: ["es2015"] })
.code; .code;
assert.equal(output, "42;"); expect(output).toBe("42;");
}); });
it("handles the react preset", () => { it("handles the react preset", () => {
@ -70,8 +67,7 @@ const assert = require("assert");
presets: ["react"], presets: ["react"],
}, },
).code; ).code;
assert.equal( expect(output).toBe(
output,
'const someDiv = React.createElement("div", null, getMessage());', 'const someDiv = React.createElement("div", null, getMessage());',
); );
}); });
@ -80,7 +76,7 @@ const assert = require("assert");
const output = Babel.transform("export let x", { const output = Babel.transform("export let x", {
presets: [["es2015", { modules: false }]], presets: [["es2015", { modules: false }]],
}).code; }).code;
assert.equal(output, "export var x;"); expect(output).toBe("export var x;");
}); });
it("handles specifying a plugin by name", () => { it("handles specifying a plugin by name", () => {
@ -88,8 +84,7 @@ const assert = require("assert");
plugins: ["transform-arrow-functions"], plugins: ["transform-arrow-functions"],
}).code; }).code;
// Transforms arrow syntax but NOT "const". // Transforms arrow syntax but NOT "const".
assert.equal( expect(output).toBe(
output,
"const getMessage = function () {\n" + "const getMessage = function () {\n" +
' return "Hello World";\n' + ' return "Hello World";\n' +
"};", "};",
@ -100,21 +95,19 @@ const assert = require("assert");
const output = Babel.transform("`${x}`", { const output = Babel.transform("`${x}`", {
plugins: [["transform-template-literals", { loose: true }]], plugins: [["transform-template-literals", { loose: true }]],
}).code; }).code;
assert.equal(output, '"" + x;'); expect(output).toBe('"" + x;');
}); });
it("throws on invalid preset name", () => { it("throws on invalid preset name", () => {
assert.throws( expect(() =>
() => Babel.transform("var foo", { presets: ["lolfail"] }), Babel.transform("var foo", { presets: ["lolfail"] }),
/Invalid preset specified in Babel options: "lolfail"/, ).toThrow(/Invalid preset specified in Babel options: "lolfail"/);
);
}); });
it("throws on invalid plugin name", () => { it("throws on invalid plugin name", () => {
assert.throws( expect(() =>
() => Babel.transform("var foo", { plugins: ["lolfail"] }), Babel.transform("var foo", { plugins: ["lolfail"] }),
/Invalid plugin specified in Babel options: "lolfail"/, ).toThrow(/Invalid plugin specified in Babel options: "lolfail"/);
);
}); });
describe("custom plugins and presets", () => { describe("custom plugins and presets", () => {
@ -132,12 +125,9 @@ const assert = require("assert");
"function helloWorld() { alert(hello); }", "function helloWorld() { alert(hello); }",
{ plugins: ["lolizer"] }, { plugins: ["lolizer"] },
); );
assert.equal( expect(output.code).toBe(`function LOL() {
output.code,
`function LOL() {
LOL(LOL); LOL(LOL);
}`, }`);
);
}); });
it("allows custom presets to be registered", () => { it("allows custom presets to be registered", () => {
@ -146,12 +136,9 @@ const assert = require("assert");
"function helloWorld() { alert(hello); }", "function helloWorld() { alert(hello); }",
{ presets: ["lulz"] }, { presets: ["lulz"] },
); );
assert.equal( expect(output.code).toBe(`function LOL() {
output.code,
`function LOL() {
LOL(LOL); LOL(LOL);
}`, }`);
);
}); });
}); });
}, },

View File

@ -1,6 +1,5 @@
import generator from "../../babel-generator"; import generator from "../../babel-generator";
import template from "../lib"; import template from "../lib";
import { expect } from "chai";
import * as t from "@babel/types"; import * as t from "@babel/types";
const comments = "// Sum two numbers\nconst add = (a, b) => a + b;"; const comments = "// Sum two numbers\nconst add = (a, b) => a + b;";
@ -9,24 +8,24 @@ describe("@babel/template", function() {
it("import statements are allowed by default", function() { it("import statements are allowed by default", function() {
expect(function() { expect(function() {
template("import foo from 'foo'")({}); template("import foo from 'foo'")({});
}).not.to.throw(); }).not.toThrow();
}); });
it("with statements are allowed with sourceType: script", function() { it("with statements are allowed with sourceType: script", function() {
expect(function() { expect(function() {
template("with({}){}", { sourceType: "script" })({}); template("with({}){}", { sourceType: "script" })({});
}).not.to.throw(); }).not.toThrow();
}); });
it("should strip comments by default", function() { it("should strip comments by default", function() {
const code = "const add = (a, b) => a + b;"; const code = "const add = (a, b) => a + b;";
const output = template(comments)(); const output = template(comments)();
expect(generator(output).code).to.be.equal(code); expect(generator(output).code).toBe(code);
}); });
it("should preserve comments with a flag", function() { it("should preserve comments with a flag", function() {
const output = template(comments, { preserveComments: true })(); const output = template(comments, { preserveComments: true })();
expect(generator(output).code).to.be.equal(comments); expect(generator(output).code).toBe(comments);
}); });
describe("string-based", () => { describe("string-based", () => {
@ -38,9 +37,9 @@ describe("@babel/template", function() {
SOME_VAR: value, SOME_VAR: value,
}); });
expect(result.type).to.equal("IfStatement"); expect(result.type).toBe("IfStatement");
expect(result.test.type).to.equal("BinaryExpression"); expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left).to.equal(value); expect(result.test.left).toBe(value);
}); });
it("should handle replacing values given an array", () => { it("should handle replacing values given an array", () => {
@ -49,9 +48,9 @@ describe("@babel/template", function() {
if ($0 === "") {} if ($0 === "") {}
`)([value]); `)([value]);
expect(result.type).to.equal("IfStatement"); expect(result.type).toBe("IfStatement");
expect(result.test.type).to.equal("BinaryExpression"); expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left).to.equal(value); expect(result.test.left).toBe(value);
}); });
it("should handle replacing values with null to remove them", () => { it("should handle replacing values with null to remove them", () => {
@ -59,9 +58,9 @@ describe("@babel/template", function() {
callee(ARG); callee(ARG);
`)({ ARG: null }); `)({ ARG: null });
expect(result.type).to.equal("ExpressionStatement"); expect(result.type).toBe("ExpressionStatement");
expect(result.expression.type).to.equal("CallExpression"); expect(result.expression.type).toBe("CallExpression");
expect(result.expression.arguments).to.eql([]); expect(result.expression.arguments).toEqual([]);
}); });
it("should handle replacing values that are string content", () => { it("should handle replacing values that are string content", () => {
@ -69,9 +68,9 @@ describe("@babel/template", function() {
("ARG"); ("ARG");
`)({ ARG: "some new content" }); `)({ ARG: "some new content" });
expect(result.type).to.equal("ExpressionStatement"); expect(result.type).toBe("ExpressionStatement");
expect(result.expression.type).to.equal("StringLiteral"); expect(result.expression.type).toBe("StringLiteral");
expect(result.expression.value).to.equal("some new content"); expect(result.expression.value).toBe("some new content");
}); });
it("should automatically clone nodes if they are injected twice", () => { it("should automatically clone nodes if they are injected twice", () => {
@ -82,11 +81,11 @@ describe("@babel/template", function() {
ID; ID;
`)({ ID: id }); `)({ ID: id });
expect(result[0].type).to.equal("ExpressionStatement"); expect(result[0].type).toBe("ExpressionStatement");
expect(result[0].expression).to.equal(id); expect(result[0].expression).toBe(id);
expect(result[1].type).to.equal("ExpressionStatement"); expect(result[1].type).toBe("ExpressionStatement");
expect(result[1].expression).not.to.equal(id); expect(result[1].expression).not.toBe(id);
expect(result[1].expression).to.eql(id); expect(result[1].expression).toEqual(id);
}); });
it("should allow passing in a whitelist of replacement names", () => { it("should allow passing in a whitelist of replacement names", () => {
@ -98,8 +97,8 @@ describe("@babel/template", function() {
{ placeholderWhitelist: new Set(["some_id"]) }, { placeholderWhitelist: new Set(["some_id"]) },
)({ some_id: id }); )({ some_id: id });
expect(result.type).to.equal("ExpressionStatement"); expect(result.type).toBe("ExpressionStatement");
expect(result.expression).to.equal(id); expect(result.expression).toBe(id);
}); });
it("should allow passing in a RegExp to match replacement patterns", () => { it("should allow passing in a RegExp to match replacement patterns", () => {
@ -112,11 +111,11 @@ describe("@babel/template", function() {
{ placeholderPattern: /^ID$/ }, { placeholderPattern: /^ID$/ },
)({ ID: id }); )({ ID: id });
expect(result[0].type).to.equal("ExpressionStatement"); expect(result[0].type).toBe("ExpressionStatement");
expect(result[0].expression).to.equal(id); expect(result[0].expression).toBe(id);
expect(result[1].type).to.equal("ExpressionStatement"); expect(result[1].type).toBe("ExpressionStatement");
expect(result[1].expression.type).to.equal("Identifier"); expect(result[1].expression.type).toBe("Identifier");
expect(result[1].expression.name).to.equal("ANOTHER_ID"); expect(result[1].expression.name).toBe("ANOTHER_ID");
}); });
it("should throw if unknown replacements are provided", () => { it("should throw if unknown replacements are provided", () => {
@ -124,7 +123,7 @@ describe("@babel/template", function() {
template(` template(`
ID; ID;
`)({ ID: t.identifier("someIdent"), ANOTHER_ID: null }); `)({ ID: t.identifier("someIdent"), ANOTHER_ID: null });
}).to.throw(Error, 'Unknown substitution "ANOTHER_ID" given'); }).toThrow('Unknown substitution "ANOTHER_ID" given');
}); });
it("should throw if placeholders are not given explicit values", () => { it("should throw if placeholders are not given explicit values", () => {
@ -133,8 +132,7 @@ describe("@babel/template", function() {
ID; ID;
ANOTHER_ID; ANOTHER_ID;
`)({ ID: t.identifier("someIdent") }); `)({ ID: t.identifier("someIdent") });
}).to.throw( }).toThrow(
Error,
`Error: No substitution given for "ANOTHER_ID". If this is not meant to be a `Error: No substitution given for "ANOTHER_ID". If this is not meant to be a
placeholder you may want to consider passing one of the following options to @babel/template: placeholder you may want to consider passing one of the following options to @babel/template:
- { placeholderPattern: false, placeholderWhitelist: new Set(['ANOTHER_ID'])} - { placeholderPattern: false, placeholderWhitelist: new Set(['ANOTHER_ID'])}
@ -147,10 +145,10 @@ describe("@babel/template", function() {
if ("some string value" === "") {} if ("some string value" === "") {}
`); `);
expect(result.type).to.equal("IfStatement"); expect(result.type).toBe("IfStatement");
expect(result.test.type).to.equal("BinaryExpression"); expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left.type).to.equal("StringLiteral"); expect(result.test.left.type).toBe("StringLiteral");
expect(result.test.left.value).to.equal("some string value"); expect(result.test.left.value).toBe("some string value");
}); });
}); });
@ -161,9 +159,9 @@ describe("@babel/template", function() {
if (${value} === "") {} if (${value} === "") {}
`(); `();
expect(result.type).to.equal("IfStatement"); expect(result.type).toBe("IfStatement");
expect(result.test.type).to.equal("BinaryExpression"); expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left).to.equal(value); expect(result.test.left).toBe(value);
}); });
it("should handle replacing values with null to remove them", () => { it("should handle replacing values with null to remove them", () => {
@ -171,9 +169,9 @@ describe("@babel/template", function() {
callee(${null}); callee(${null});
`(); `();
expect(result.type).to.equal("ExpressionStatement"); expect(result.type).toBe("ExpressionStatement");
expect(result.expression.type).to.equal("CallExpression"); expect(result.expression.type).toBe("CallExpression");
expect(result.expression.arguments).to.eql([]); expect(result.expression.arguments).toEqual([]);
}); });
it("should handle replacing values that are string content", () => { it("should handle replacing values that are string content", () => {
@ -181,9 +179,9 @@ describe("@babel/template", function() {
("${"some new content"}"); ("${"some new content"}");
`(); `();
expect(result.type).to.equal("ExpressionStatement"); expect(result.type).toBe("ExpressionStatement");
expect(result.expression.type).to.equal("StringLiteral"); expect(result.expression.type).toBe("StringLiteral");
expect(result.expression.value).to.equal("some new content"); expect(result.expression.value).toBe("some new content");
}); });
it("should allow setting options by passing an object", () => { it("should allow setting options by passing an object", () => {
@ -191,7 +189,7 @@ describe("@babel/template", function() {
with({}){} with({}){}
`(); `();
expect(result.type).to.equal("WithStatement"); expect(result.type).toBe("WithStatement");
}); });
it("should return the AST directly when using .ast", () => { it("should return the AST directly when using .ast", () => {
@ -200,9 +198,9 @@ describe("@babel/template", function() {
if (${value} === "") {} if (${value} === "") {}
`; `;
expect(result.type).to.equal("IfStatement"); expect(result.type).toBe("IfStatement");
expect(result.test.type).to.equal("BinaryExpression"); expect(result.test.type).toBe("BinaryExpression");
expect(result.test.left).to.equal(value); expect(result.test.left).toBe(value);
}); });
it("should replace JSX placeholder", () => { it("should replace JSX placeholder", () => {

View File

@ -1,7 +1,5 @@
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
import { expect } from "chai";
describe("path/ancestry", function() { describe("path/ancestry", function() {
describe("isAncestor", function() { describe("isAncestor", function() {
@ -17,7 +15,7 @@ describe("path/ancestry", function() {
const [programPath, numberPath] = paths; const [programPath, numberPath] = paths;
assert(programPath.isAncestor(numberPath)); expect(programPath.isAncestor(numberPath)).toBeTruthy();
}); });
it("returns false if not ancestor", function() { it("returns false if not ancestor", function() {
@ -30,7 +28,7 @@ describe("path/ancestry", function() {
const [, numberPath, stringPath] = paths; const [, numberPath, stringPath] = paths;
assert(!stringPath.isAncestor(numberPath)); expect(stringPath.isAncestor(numberPath)).toBeFalsy();
}); });
}); });
@ -47,7 +45,7 @@ describe("path/ancestry", function() {
const [programPath, numberPath] = paths; const [programPath, numberPath] = paths;
assert(numberPath.isDescendant(programPath)); expect(numberPath.isDescendant(programPath)).toBeTruthy();
}); });
it("returns false if not descendant", function() { it("returns false if not descendant", function() {
@ -60,7 +58,7 @@ describe("path/ancestry", function() {
const [, numberPath, stringPath] = paths; const [, numberPath, stringPath] = paths;
assert(!numberPath.isDescendant(stringPath)); expect(numberPath.isDescendant(stringPath)).toBeFalsy();
}); });
}); });
@ -73,7 +71,7 @@ describe("path/ancestry", function() {
path.getStatementParent(); path.getStatementParent();
}, },
}); });
}).to.throw(/File\/Program node/); }).toThrow(/File\/Program node/);
}); });
}); });
}); });

View File

@ -1,5 +1,4 @@
import { NodePath } from "../lib"; import { NodePath } from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
import generate from "@babel/generator"; import generate from "@babel/generator";
import * as t from "@babel/types"; import * as t from "@babel/types";
@ -35,7 +34,7 @@ function assertConversion(
}, },
}); });
assert.equal(generate(inputAst).code, generate(outputAst).code); expect(generate(inputAst).code).toBe(generate(outputAst).code);
} }
function wrapMethod(body, methodName, extend) { function wrapMethod(body, methodName, extend) {

View File

@ -1,5 +1,4 @@
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
import generate from "@babel/generator"; import generate from "@babel/generator";
import * as t from "@babel/types"; import * as t from "@babel/types";
@ -26,22 +25,22 @@ describe("conversion", function() {
it("throws converting node without body to block", function() { it("throws converting node without body to block", function() {
const rootPath = getPath("true;"); const rootPath = getPath("true;");
assert.throws(() => { expect(() => {
rootPath.ensureBlock(); rootPath.ensureBlock();
}, /Can't convert node without a body/); }).toThrow();
}); });
it("throws converting already block array", function() { it("throws converting already block array", function() {
const rootPath = getPath("function test() { true; }").get("body"); const rootPath = getPath("function test() { true; }").get("body");
assert.throws(() => { expect(() => {
rootPath.ensureBlock(); rootPath.ensureBlock();
}, /Can't convert array path to a block statement/); }).toThrow();
}); });
it("converts arrow function with expression body to block", function() { it("converts arrow function with expression body to block", function() {
const rootPath = getPath("() => true").get("expression"); const rootPath = getPath("() => true").get("expression");
rootPath.ensureBlock(); rootPath.ensureBlock();
assert.equal(generateCode(rootPath), "() => {\n return true;\n};"); expect(generateCode(rootPath)).toBe("() => {\n return true;\n};");
}); });
it("preserves arrow function body's context", function() { it("preserves arrow function body's context", function() {
@ -49,13 +48,13 @@ describe("conversion", function() {
const body = rootPath.get("body"); const body = rootPath.get("body");
rootPath.ensureBlock(); rootPath.ensureBlock();
body.replaceWith(t.booleanLiteral(false)); body.replaceWith(t.booleanLiteral(false));
assert.equal(generateCode(rootPath), "() => {\n return false;\n};"); expect(generateCode(rootPath)).toBe("() => {\n return false;\n};");
}); });
it("converts for loop with statement body to block", function() { it("converts for loop with statement body to block", function() {
const rootPath = getPath("for (;;) true;"); const rootPath = getPath("for (;;) true;");
rootPath.ensureBlock(); rootPath.ensureBlock();
assert.equal(generateCode(rootPath), "for (;;) {\n true;\n}"); expect(generateCode(rootPath)).toBe("for (;;) {\n true;\n}");
}); });
it("preserves for loop body's context", function() { it("preserves for loop body's context", function() {
@ -63,7 +62,7 @@ describe("conversion", function() {
const body = rootPath.get("body"); const body = rootPath.get("body");
rootPath.ensureBlock(); rootPath.ensureBlock();
body.replaceWith(t.booleanLiteral(false)); body.replaceWith(t.booleanLiteral(false));
assert.equal(generateCode(rootPath), "for (;;) {\n false;\n}"); expect(generateCode(rootPath)).toBe("for (;;) {\n false;\n}");
}); });
}); });
}); });

View File

@ -1,5 +1,4 @@
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
function getPath(code) { function getPath(code) {
@ -17,76 +16,68 @@ function getPath(code) {
describe("evaluation", function() { describe("evaluation", function() {
describe("evaluateTruthy", function() { describe("evaluateTruthy", function() {
it("it should work with null", function() { it("it should work with null", function() {
assert.strictEqual( expect(
getPath("false || a.length === 0;") getPath("false || a.length === 0;")
.get("body")[0] .get("body")[0]
.evaluateTruthy(), .evaluateTruthy(),
undefined, ).toBeUndefined();
);
}); });
it("it should not mistake lack of confidence for falsy", function() { it("it should not mistake lack of confidence for falsy", function() {
assert.strictEqual( expect(
getPath("foo || 'bar'") getPath("foo || 'bar'")
.get("body")[0] .get("body")[0]
.evaluate().value, .evaluate().value,
undefined, ).toBeUndefined();
);
}); });
}); });
it("should bail out on recursive evaluation", function() { it("should bail out on recursive evaluation", function() {
assert.strictEqual( expect(
getPath("function fn(a) { var g = a ? 1 : 2, a = g * this.foo; }") getPath("function fn(a) { var g = a ? 1 : 2, a = g * this.foo; }")
.get("body.0.body.body.0.declarations.1.init") .get("body.0.body.body.0.declarations.1.init")
.evaluate().confident, .evaluate().confident,
false, ).toBe(false);
);
}); });
it("should work with repeated, indeterminate identifiers", function() { it("should work with repeated, indeterminate identifiers", function() {
assert.strictEqual( expect(
getPath("var num = foo(); (num > 0 && num < 100);") getPath("var num = foo(); (num > 0 && num < 100);")
.get("body")[1] .get("body")[1]
.evaluateTruthy(), .evaluateTruthy(),
undefined, ).toBeUndefined();
);
}); });
it("should work with repeated, determinate identifiers", function() { it("should work with repeated, determinate identifiers", function() {
assert.strictEqual( expect(
getPath("var num = 5; (num > 0 && num < 100);") getPath("var num = 5; (num > 0 && num < 100);")
.get("body")[1] .get("body")[1]
.evaluateTruthy(), .evaluateTruthy(),
true, ).toBe(true);
);
}); });
it("should deopt when var is redeclared in the same scope", function() { it("should deopt when var is redeclared in the same scope", function() {
assert.strictEqual( expect(
getPath("var x = 2; var y = x + 2; { var x = 3 }") getPath("var x = 2; var y = x + 2; { var x = 3 }")
.get("body.1.declarations.0.init") .get("body.1.declarations.0.init")
.evaluate().confident, .evaluate().confident,
false, ).toBe(false);
);
}); });
it("should evaluate template literals", function() { it("should evaluate template literals", function() {
assert.strictEqual( expect(
getPath("var x = 8; var y = 1; var z = `value is ${x >>> y}`") getPath("var x = 8; var y = 1; var z = `value is ${x >>> y}`")
.get("body.2.declarations.0.init") .get("body.2.declarations.0.init")
.evaluate().value, .evaluate().value,
"value is 4", ).toBe("value is 4");
);
}); });
it("should evaluate member expressions", function() { it("should evaluate member expressions", function() {
assert.strictEqual( expect(
getPath("var x = 'foo'.length") getPath("var x = 'foo'.length")
.get("body.0.declarations.0.init") .get("body.0.declarations.0.init")
.evaluate().value, .evaluate().value,
3, ).toBe(3);
);
const member_expr = getPath( const member_expr = getPath(
"var x = Math.min(2,Math.max(3,4));var y = Math.random();", "var x = Math.min(2,Math.max(3,4));var y = Math.random();",
); );
@ -96,91 +87,80 @@ describe("evaluation", function() {
const eval_invalid_call = member_expr const eval_invalid_call = member_expr
.get("body.1.declarations.0.init") .get("body.1.declarations.0.init")
.evaluate(); .evaluate();
assert.strictEqual(eval_member_expr.value, 2); expect(eval_member_expr.value).toBe(2);
assert.strictEqual(eval_invalid_call.confident, false); expect(eval_invalid_call.confident).toBe(false);
}); });
it("it should not deopt vars in different scope", function() { it("it should not deopt vars in different scope", function() {
const input = const input =
"var a = 5; function x() { var a = 5; var b = a + 1; } var b = a + 2"; "var a = 5; function x() { var a = 5; var b = a + 1; } var b = a + 2";
assert.strictEqual( expect(
getPath(input) getPath(input)
.get("body.1.body.body.1.declarations.0.init") .get("body.1.body.body.1.declarations.0.init")
.evaluate().value, .evaluate().value,
6, ).toBe(6);
); expect(
assert.strictEqual(
getPath(input) getPath(input)
.get("body.2.declarations.0.init") .get("body.2.declarations.0.init")
.evaluate().value, .evaluate().value,
7, ).toBe(7);
);
}); });
it("it should not deopt let/const inside blocks", function() { it("it should not deopt let/const inside blocks", function() {
assert.strictEqual( expect(
getPath("let x = 5; { let x = 1; } let y = x + 5") getPath("let x = 5; { let x = 1; } let y = x + 5")
.get("body.2.declarations.0.init") .get("body.2.declarations.0.init")
.evaluate().value, .evaluate().value,
10, ).toBe(10);
);
const constExample = const constExample =
"const d = true; if (d && true || false) { const d = false; d && 5; }"; "const d = true; if (d && true || false) { const d = false; d && 5; }";
assert.strictEqual( expect(
getPath(constExample) getPath(constExample)
.get("body.1.test") .get("body.1.test")
.evaluate().value, .evaluate().value,
true, ).toBe(true);
); expect(
assert.strictEqual(
getPath(constExample) getPath(constExample)
.get("body.1.consequent.body.1") .get("body.1.consequent.body.1")
.evaluate().value, .evaluate().value,
false, ).toBe(false);
);
const test_alternate = "var y = (3 < 4)? 3 + 4: 3 + 4;"; const test_alternate = "var y = (3 < 4)? 3 + 4: 3 + 4;";
assert.strictEqual( expect(
getPath(test_alternate) getPath(test_alternate)
.get("body.0.declarations.0.init.alternate") .get("body.0.declarations.0.init.alternate")
.evaluate().value, .evaluate().value,
7, ).toBe(7);
);
}); });
it("should deopt ids that are referenced before the bindings", function() { it("should deopt ids that are referenced before the bindings", function() {
assert.strictEqual( expect(
getPath("let x = y + 5; let y = 5;") getPath("let x = y + 5; let y = 5;")
.get("body.0.declarations.0.init") .get("body.0.declarations.0.init")
.evaluate().confident, .evaluate().confident,
false, ).toBe(false);
); expect(
assert.strictEqual(
getPath("if (typeof x === 'undefined') var x = {}") getPath("if (typeof x === 'undefined') var x = {}")
.get("body.0.test") .get("body.0.test")
.evaluate().confident, .evaluate().confident,
false, ).toBe(false);
);
}); });
it("should evaluate undefined, NaN and Infinity", () => { it("should evaluate undefined, NaN and Infinity", () => {
assert.strictEqual( expect(
getPath("undefined") getPath("undefined")
.get("body.0.expression") .get("body.0.expression")
.evaluate().confident, .evaluate().confident,
true, ).toBe(true);
); expect(
assert.strictEqual(
getPath("NaN") getPath("NaN")
.get("body.0.expression") .get("body.0.expression")
.evaluate().confident, .evaluate().confident,
true, ).toBe(true);
); expect(
assert.strictEqual(
getPath("Infinity") getPath("Infinity")
.get("body.0.expression") .get("body.0.expression")
.evaluate().confident, .evaluate().confident,
true, ).toBe(true);
);
}); });
it("should deopt redefined primitives - undefined, NaN and Infinity", () => { it("should deopt redefined primitives - undefined, NaN and Infinity", () => {
@ -193,28 +173,26 @@ describe("evaluation", function() {
const eval_inf = getPath("let Infinity; Infinity;") const eval_inf = getPath("let Infinity; Infinity;")
.get("body.1.expression") .get("body.1.expression")
.evaluate(); .evaluate();
assert.strictEqual(eval_undef.confident, false); expect(eval_undef.confident).toBe(false);
assert.strictEqual(eval_nan.confident, false); expect(eval_nan.confident).toBe(false);
assert.strictEqual(eval_inf.confident, false); expect(eval_inf.confident).toBe(false);
assert.strictEqual(eval_undef.deopt.type, "VariableDeclarator"); expect(eval_undef.deopt.type).toBe("VariableDeclarator");
assert.strictEqual(eval_undef.deopt.parentPath.node.kind, "let"); expect(eval_undef.deopt.parentPath.node.kind).toBe("let");
}); });
it("should work with String.raw", function() { it("should work with String.raw", function() {
assert.strictEqual( expect(
getPath("String.raw`\\d`") getPath("String.raw`\\d`")
.get("body")[0] .get("body")[0]
.evaluate().value, .evaluate().value,
"\\d", ).toBe("\\d");
);
assert.strictEqual( expect(
getPath("`${String.raw`\\d`}`") getPath("`${String.raw`\\d`}`")
.get("body")[0] .get("body")[0]
.evaluate().value, .evaluate().value,
"\\d", ).toBe("\\d");
);
}); });
it("sets deopt properly when not confident after evaluating multiple expressions", () => { it("sets deopt properly when not confident after evaluating multiple expressions", () => {
@ -233,9 +211,9 @@ describe("evaluation", function() {
}, },
}); });
assert.strictEqual(result.confident, false); expect(result.confident).toBe(false);
assert.strictEqual(result.deopt.type, "Identifier"); expect(result.deopt.type).toBe("Identifier");
assert.strictEqual(result.deopt.node.name, "foo"); expect(result.deopt.node.name).toBe("foo");
}); });
it("sets deopt properly when confident after evaluating multiple expressions", () => { it("sets deopt properly when confident after evaluating multiple expressions", () => {
@ -256,8 +234,8 @@ describe("evaluation", function() {
}, },
}); });
assert.strictEqual(result.confident, true); expect(result.confident).toBe(true);
assert.strictEqual(result.deopt, null); expect(result.deopt).toBeNull();
assert.deepStrictEqual(result.value, ["foo", "bar"]); expect(result.value).toEqual(["foo", "bar"]);
}); });
}); });

View File

@ -1,5 +1,4 @@
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
describe("path/family", function() { describe("path/family", function() {
@ -22,45 +21,37 @@ describe("path/family", function() {
it("should contain keys of nodes in paths", function() { it("should contain keys of nodes in paths", function() {
Object.keys(nodes).forEach(id => { Object.keys(nodes).forEach(id => {
assert.strictEqual(hop(paths, id), true, "Node's keys exists in paths"); expect(hop(paths, id)).toBe(true);
}); });
}); });
it("should contain outer bindings", function() { it("should contain outer bindings", function() {
Object.keys(outerNodes).forEach(id => { Object.keys(outerNodes).forEach(id => {
assert.strictEqual(hop(outerPaths, id), true, "Has same outer keys"); expect(hop(outerPaths, id)).toBe(true);
}); });
}); });
it("should return paths", function() { it("should return paths", function() {
Object.keys(paths).forEach(id => { Object.keys(paths).forEach(id => {
assert.strictEqual( expect(paths[id].node).toBeTruthy();
!!paths[id].node, expect(paths[id].type).toBe(paths[id].node.type);
true,
"Has a property node that's not falsy",
);
assert.strictEqual(paths[id].type, paths[id].node.type, "type matches");
}); });
Object.keys(outerPaths).forEach(id => { Object.keys(outerPaths).forEach(id => {
assert.strictEqual(!!outerPaths[id].node, true, "has property node"); expect(outerPaths[id].node).toBeTruthy();
assert.strictEqual( expect(outerPaths[id].type).toBe(outerPaths[id].node.type);
outerPaths[id].type,
outerPaths[id].node.type,
"type matches",
);
}); });
}); });
it("should match paths and nodes returned for the same ast", function() { it("should match paths and nodes returned for the same ast", function() {
Object.keys(nodes).forEach(id => { Object.keys(nodes).forEach(id => {
assert.strictEqual(nodes[id], paths[id].node, "Nodes match"); expect(nodes[id]).toBe(paths[id].node);
}); });
}); });
it("should match paths and nodes returned for outer Bindings", function() { it("should match paths and nodes returned for outer Bindings", function() {
Object.keys(outerNodes).forEach(id => { Object.keys(outerNodes).forEach(id => {
assert.strictEqual(outerNodes[id], outerPaths[id].node, "nodes match"); expect(outerNodes[id]).toBe(outerPaths[id].node);
}); });
}); });
}); });
@ -78,25 +69,17 @@ describe("path/family", function() {
}); });
it("should return traverse sibling nodes", function() { it("should return traverse sibling nodes", function() {
assert.ok(sibling.getNextSibling().node, "has property node"); expect(sibling.getNextSibling().node).toBeTruthy();
assert.ok(lastSibling.getPrevSibling().node, "has property node"); expect(lastSibling.getPrevSibling().node).toBeTruthy();
assert.equal(!!sibling.getPrevSibling().node, false, "out of scope"); expect(sibling.getPrevSibling().node).toBeFalsy();
assert.equal(!!lastSibling.getNextSibling().node, false, "out of scope"); expect(lastSibling.getNextSibling().node).toBeFalsy();
}); });
it("should return all preceding and succeeding sibling nodes", function() { it("should return all preceding and succeeding sibling nodes", function() {
assert.ok(sibling.getAllNextSiblings().length, "Has next sibling"); expect(sibling.getAllNextSiblings().length).toBeTruthy();
assert.ok(lastSibling.getAllPrevSiblings().length, "Has prev sibling"); expect(lastSibling.getAllPrevSiblings().length).toBeTruthy();
assert.equal( expect(sibling.getAllNextSiblings()).toHaveLength(2);
sibling.getAllNextSiblings().length, expect(lastSibling.getAllPrevSiblings()).toHaveLength(2);
2,
"Has 2 succeeding sibling",
);
assert.equal(
lastSibling.getAllPrevSiblings().length,
2,
"Has 2 preceeding sibling",
);
}); });
}); });
}); });

View File

@ -1,5 +1,4 @@
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
import * as t from "@babel/types"; import * as t from "@babel/types";
@ -25,7 +24,7 @@ describe("inference", function() {
const right = path.get("right"); const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right); const strictMatch = left.baseTypeStrictlyMatches(right);
assert.ok(strictMatch, "null should be equal to null"); expect(strictMatch).toBeTruthy();
}); });
it("it should work with numbers", function() { it("it should work with numbers", function() {
@ -36,7 +35,7 @@ describe("inference", function() {
const right = path.get("right"); const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right); const strictMatch = left.baseTypeStrictlyMatches(right);
assert.ok(strictMatch, "number should be equal to number"); expect(strictMatch).toBeTruthy();
}); });
it("it should bail when type changes", function() { it("it should bail when type changes", function() {
@ -48,7 +47,7 @@ describe("inference", function() {
const strictMatch = left.baseTypeStrictlyMatches(right); const strictMatch = left.baseTypeStrictlyMatches(right);
assert.ok(!strictMatch, "type might change in if statement"); expect(strictMatch).toBeFalsy();
}); });
it("it should differentiate between null and undefined", function() { it("it should differentiate between null and undefined", function() {
@ -59,7 +58,7 @@ describe("inference", function() {
const right = path.get("right"); const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right); const strictMatch = left.baseTypeStrictlyMatches(right);
assert.ok(!strictMatch, "null should not match undefined"); expect(strictMatch).toBeFalsy();
}); });
}); });
describe("getTypeAnnotation", function() { describe("getTypeAnnotation", function() {
@ -67,247 +66,194 @@ describe("inference", function() {
const path = getPath("(x: number)") const path = getPath("(x: number)")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
assert.ok( expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy();
t.isNumberTypeAnnotation(path.getTypeAnnotation()),
"should be number",
);
}); });
it("should infer string from template literal", function() { it("should infer string from template literal", function() {
const path = getPath("`hey`") const path = getPath("`hey`")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
assert.ok( expect(t.isStringTypeAnnotation(path.getTypeAnnotation())).toBeTruthy();
t.isStringTypeAnnotation(path.getTypeAnnotation()),
"should be string",
);
}); });
it("should infer number from +x", function() { it("should infer number from +x", function() {
const path = getPath("+x") const path = getPath("+x")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
assert.ok( expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy();
t.isNumberTypeAnnotation(path.getTypeAnnotation()),
"should be number",
);
}); });
it("should infer T from new T", function() { it("should infer T from new T", function() {
const path = getPath("new T") const path = getPath("new T")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok( expect(
t.isGenericTypeAnnotation(type) && type.id.name === "T", t.isGenericTypeAnnotation(type) && type.id.name === "T",
"should be T", ).toBeTruthy();
);
}); });
it("should infer number from ++x", function() { it("should infer number from ++x", function() {
const path = getPath("++x") const path = getPath("++x")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
assert.ok( expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy();
t.isNumberTypeAnnotation(path.getTypeAnnotation()),
"should be number",
);
}); });
it("should infer number from --x", function() { it("should infer number from --x", function() {
const path = getPath("--x") const path = getPath("--x")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
assert.ok( expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy();
t.isNumberTypeAnnotation(path.getTypeAnnotation()),
"should be number",
);
}); });
it("should infer void from void x", function() { it("should infer void from void x", function() {
const path = getPath("void x") const path = getPath("void x")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
assert.ok( expect(t.isVoidTypeAnnotation(path.getTypeAnnotation())).toBeTruthy();
t.isVoidTypeAnnotation(path.getTypeAnnotation()),
"should be void",
);
}); });
it("should infer string from typeof x", function() { it("should infer string from typeof x", function() {
const path = getPath("typeof x") const path = getPath("typeof x")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
assert.ok( expect(t.isStringTypeAnnotation(path.getTypeAnnotation())).toBeTruthy();
t.isStringTypeAnnotation(path.getTypeAnnotation()),
"should be string",
);
}); });
it("should infer boolean from !x", function() { it("should infer boolean from !x", function() {
const path = getPath("!x") const path = getPath("!x")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
assert.ok( expect(t.isBooleanTypeAnnotation(path.getTypeAnnotation())).toBeTruthy();
t.isBooleanTypeAnnotation(path.getTypeAnnotation()),
"should be boolean",
);
}); });
it("should infer type of sequence expression", function() { it("should infer type of sequence expression", function() {
const path = getPath("a,1") const path = getPath("a,1")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
assert.ok( expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy();
t.isNumberTypeAnnotation(path.getTypeAnnotation()),
"should be number",
);
}); });
it("should infer type of logical expression", function() { it("should infer type of logical expression", function() {
const path = getPath("'a' && 1") const path = getPath("'a' && 1")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isUnionTypeAnnotation(type), "should be a union"); expect(t.isUnionTypeAnnotation(type)).toBeTruthy();
assert.ok( expect(t.isStringTypeAnnotation(type.types[0])).toBeTruthy();
t.isStringTypeAnnotation(type.types[0]), expect(t.isNumberTypeAnnotation(type.types[1])).toBeTruthy();
"first type in union should be string",
);
assert.ok(
t.isNumberTypeAnnotation(type.types[1]),
"second type in union should be number",
);
}); });
it("should infer type of conditional expression", function() { it("should infer type of conditional expression", function() {
const path = getPath("q ? true : 0") const path = getPath("q ? true : 0")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isUnionTypeAnnotation(type), "should be a union"); expect(t.isUnionTypeAnnotation(type)).toBeTruthy();
assert.ok( expect(t.isBooleanTypeAnnotation(type.types[0])).toBeTruthy();
t.isBooleanTypeAnnotation(type.types[0]), expect(t.isNumberTypeAnnotation(type.types[1])).toBeTruthy();
"first type in union should be boolean",
);
assert.ok(
t.isNumberTypeAnnotation(type.types[1]),
"second type in union should be number",
);
}); });
it("should infer RegExp from RegExp literal", function() { it("should infer RegExp from RegExp literal", function() {
const path = getPath("/.+/") const path = getPath("/.+/")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok( expect(
t.isGenericTypeAnnotation(type) && type.id.name === "RegExp", t.isGenericTypeAnnotation(type) && type.id.name === "RegExp",
"should be RegExp", ).toBeTruthy();
);
}); });
it("should infer Object from object expression", function() { it("should infer Object from object expression", function() {
const path = getPath("({ a: 5 })") const path = getPath("({ a: 5 })")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok( expect(
t.isGenericTypeAnnotation(type) && type.id.name === "Object", t.isGenericTypeAnnotation(type) && type.id.name === "Object",
"should be Object", ).toBeTruthy();
);
}); });
it("should infer Array from array expression", function() { it("should infer Array from array expression", function() {
const path = getPath("[ 5 ]") const path = getPath("[ 5 ]")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok( expect(
t.isGenericTypeAnnotation(type) && type.id.name === "Array", t.isGenericTypeAnnotation(type) && type.id.name === "Array",
"should be Array", ).toBeTruthy();
);
}); });
it("should infer Function from function", function() { it("should infer Function from function", function() {
const path = getPath("(function (): string {})") const path = getPath("(function (): string {})")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok( expect(
t.isGenericTypeAnnotation(type) && type.id.name === "Function", t.isGenericTypeAnnotation(type) && type.id.name === "Function",
"should be Function", ).toBeTruthy();
);
}); });
it("should infer call return type using function", function() { it("should infer call return type using function", function() {
const path = getPath("(function (): string {})()") const path = getPath("(function (): string {})()")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isStringTypeAnnotation(type), "should be string"); expect(t.isStringTypeAnnotation(type)).toBeTruthy();
}); });
it("should infer call return type using async function", function() { it("should infer call return type using async function", function() {
const path = getPath("(async function (): string {})()") const path = getPath("(async function (): string {})()")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok( expect(
t.isGenericTypeAnnotation(type) && type.id.name === "Promise", t.isGenericTypeAnnotation(type) && type.id.name === "Promise",
"should be Promise", ).toBeTruthy();
);
}); });
it("should infer call return type using async generator function", function() { it("should infer call return type using async generator function", function() {
const path = getPath("(async function * (): string {})()") const path = getPath("(async function * (): string {})()")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok( expect(
t.isGenericTypeAnnotation(type) && type.id.name === "AsyncIterator", t.isGenericTypeAnnotation(type) && type.id.name === "AsyncIterator",
"should be AsyncIterator", ).toBeTruthy();
);
}); });
it("should infer number from x/y", function() { it("should infer number from x/y", function() {
const path = getPath("x/y") const path = getPath("x/y")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isNumberTypeAnnotation(type), "should be number"); expect(t.isNumberTypeAnnotation(type)).toBeTruthy();
}); });
it("should infer boolean from x instanceof y", function() { it("should infer boolean from x instanceof y", function() {
const path = getPath("x instanceof y") const path = getPath("x instanceof y")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isBooleanTypeAnnotation(type), "should be boolean"); expect(t.isBooleanTypeAnnotation(type)).toBeTruthy();
}); });
it("should infer number from 1 + 2", function() { it("should infer number from 1 + 2", function() {
const path = getPath("1 + 2") const path = getPath("1 + 2")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isNumberTypeAnnotation(type), "should be number"); expect(t.isNumberTypeAnnotation(type)).toBeTruthy();
}); });
it("should infer string|number from x + y", function() { it("should infer string|number from x + y", function() {
const path = getPath("x + y") const path = getPath("x + y")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isUnionTypeAnnotation(type), "should be a union"); expect(t.isUnionTypeAnnotation(type)).toBeTruthy();
assert.ok( expect(t.isStringTypeAnnotation(type.types[0])).toBeTruthy();
t.isStringTypeAnnotation(type.types[0]), expect(t.isNumberTypeAnnotation(type.types[1])).toBeTruthy();
"first type in union should be string",
);
assert.ok(
t.isNumberTypeAnnotation(type.types[1]),
"second type in union should be number",
);
}); });
it("should infer type of tagged template literal", function() { it("should infer type of tagged template literal", function() {
const path = getPath("(function (): RegExp {}) `hey`") const path = getPath("(function (): RegExp {}) `hey`")
.get("body")[0] .get("body")[0]
.get("expression"); .get("expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok( expect(
t.isGenericTypeAnnotation(type) && type.id.name === "RegExp", t.isGenericTypeAnnotation(type) && type.id.name === "RegExp",
"should be RegExp", ).toBeTruthy();
);
}); });
it("should infer constant identifier", function() { it("should infer constant identifier", function() {
const path = getPath("const x = 0; x").get("body.1.expression"); const path = getPath("const x = 0; x").get("body.1.expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isNumberTypeAnnotation(type), "should be number"); expect(t.isNumberTypeAnnotation(type)).toBeTruthy();
}); });
it("should infer indirect constant identifier", function() { it("should infer indirect constant identifier", function() {
const path = getPath("const x = 0; const y = x; y").get( const path = getPath("const x = 0; const y = x; y").get(
"body.2.expression", "body.2.expression",
); );
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isNumberTypeAnnotation(type), "should be number"); expect(t.isNumberTypeAnnotation(type)).toBeTruthy();
}); });
it("should infer identifier type from if statement (===)", function() { it("should infer identifier type from if statement (===)", function() {
const path = getPath( const path = getPath(
@ -316,7 +262,7 @@ describe("inference", function() {
}`, }`,
).get("body.0.body.body.0.consequent.expression"); ).get("body.0.body.body.0.consequent.expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isBooleanTypeAnnotation(type), "should be boolean"); expect(t.isBooleanTypeAnnotation(type)).toBeTruthy();
}); });
it("should infer identifier type from if statement (typeof)", function() { it("should infer identifier type from if statement (typeof)", function() {
let path = getPath( let path = getPath(
@ -325,14 +271,14 @@ describe("inference", function() {
}`, }`,
).get("body.0.body.body.0.consequent.expression"); ).get("body.0.body.body.0.consequent.expression");
let type = path.getTypeAnnotation(); let type = path.getTypeAnnotation();
assert.ok(t.isStringTypeAnnotation(type), "should be string"); expect(t.isStringTypeAnnotation(type)).toBeTruthy();
path = getPath( path = getPath(
`function test(x) { `function test(x) {
if (typeof x === 'number') x; if (typeof x === 'number') x;
}`, }`,
).get("body.0.body.body.0.consequent.expression"); ).get("body.0.body.body.0.consequent.expression");
type = path.getTypeAnnotation(); type = path.getTypeAnnotation();
assert.ok(t.isNumberTypeAnnotation(type), "should be string"); expect(t.isNumberTypeAnnotation(type)).toBeTruthy();
}); });
it("should infer identifier type from if statement (&&)", function() { it("should infer identifier type from if statement (&&)", function() {
let path = getPath( let path = getPath(
@ -341,29 +287,23 @@ describe("inference", function() {
}`, }`,
).get("body.0.body.body.0.consequent.expression"); ).get("body.0.body.body.0.consequent.expression");
let type = path.getTypeAnnotation(); let type = path.getTypeAnnotation();
assert.ok(t.isUnionTypeAnnotation(type), "should be a union"); expect(t.isUnionTypeAnnotation(type)).toBeTruthy();
assert.ok( expect(t.isStringTypeAnnotation(type.types[0])).toBeTruthy();
t.isStringTypeAnnotation(type.types[0]), expect(t.isNumberTypeAnnotation(type.types[1])).toBeTruthy();
"first type in union should be string",
);
assert.ok(
t.isNumberTypeAnnotation(type.types[1]),
"second type in union should be number",
);
path = getPath( path = getPath(
`function test(x) { `function test(x) {
if (true && x === 3) x; if (true && x === 3) x;
}`, }`,
).get("body.0.body.body.0.consequent.expression"); ).get("body.0.body.body.0.consequent.expression");
type = path.getTypeAnnotation(); type = path.getTypeAnnotation();
assert.ok(t.isNumberTypeAnnotation(type), "should be number"); expect(t.isNumberTypeAnnotation(type)).toBeTruthy();
path = getPath( path = getPath(
`function test(x) { `function test(x) {
if (x === 'test' && true) x; if (x === 'test' && true) x;
}`, }`,
).get("body.0.body.body.0.consequent.expression"); ).get("body.0.body.body.0.consequent.expression");
type = path.getTypeAnnotation(); type = path.getTypeAnnotation();
assert.ok(t.isStringTypeAnnotation(type), "should be string"); expect(t.isStringTypeAnnotation(type)).toBeTruthy();
}); });
it("should infer identifier type from if statement (||)", function() { it("should infer identifier type from if statement (||)", function() {
const path = getPath( const path = getPath(
@ -372,7 +312,7 @@ describe("inference", function() {
}`, }`,
).get("body.0.body.body.0.consequent.expression"); ).get("body.0.body.body.0.consequent.expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isAnyTypeAnnotation(type), "should be a any type"); expect(t.isAnyTypeAnnotation(type)).toBeTruthy();
}); });
it("should not infer identifier type from incorrect binding", function() { it("should not infer identifier type from incorrect binding", function() {
const path = getPath( const path = getPath(
@ -385,7 +325,7 @@ describe("inference", function() {
}`, }`,
).get("body.0.body.body.0.consequent.body.0.body.body.0.expression"); ).get("body.0.body.body.0.consequent.body.0.body.body.0.expression");
const type = path.getTypeAnnotation(); const type = path.getTypeAnnotation();
assert.ok(t.isAnyTypeAnnotation(type), "should be a any type"); expect(t.isAnyTypeAnnotation(type)).toBeTruthy();
}); });
}); });
}); });

View File

@ -1,5 +1,4 @@
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
import generate from "@babel/generator"; import generate from "@babel/generator";
import * as t from "@babel/types"; import * as t from "@babel/types";
@ -27,7 +26,7 @@ describe("modification", function() {
const rootPath = getPath("function test(a) {}"); const rootPath = getPath("function test(a) {}");
rootPath.pushContainer("params", t.identifier("b")); rootPath.pushContainer("params", t.identifier("b"));
assert.equal(generateCode(rootPath), "function test(a, b) {}"); expect(generateCode(rootPath)).toBe("function test(a, b) {}");
}); });
it("pushes identifier into block", function() { it("pushes identifier into block", function() {
@ -35,7 +34,7 @@ describe("modification", function() {
const path = rootPath.get("body"); const path = rootPath.get("body");
path.pushContainer("body", t.expressionStatement(t.identifier("b"))); path.pushContainer("body", t.expressionStatement(t.identifier("b")));
assert.equal(generateCode(rootPath), "function test(a) {\n b;\n}"); expect(generateCode(rootPath)).toBe("function test(a) {\n b;\n}");
}); });
}); });
describe("unshiftContainer", function() { describe("unshiftContainer", function() {
@ -43,7 +42,7 @@ describe("modification", function() {
const rootPath = getPath("function test(a) {}"); const rootPath = getPath("function test(a) {}");
rootPath.unshiftContainer("params", t.identifier("b")); rootPath.unshiftContainer("params", t.identifier("b"));
assert.equal(generateCode(rootPath), "function test(b, a) {}"); expect(generateCode(rootPath)).toBe("function test(b, a) {}");
}); });
it("unshifts identifier into block", function() { it("unshifts identifier into block", function() {
@ -51,7 +50,7 @@ describe("modification", function() {
const path = rootPath.get("body"); const path = rootPath.get("body");
path.unshiftContainer("body", t.expressionStatement(t.identifier("b"))); path.unshiftContainer("body", t.expressionStatement(t.identifier("b")));
assert.equal(generateCode(rootPath), "function test(a) {\n b;\n}"); expect(generateCode(rootPath)).toBe("function test(a) {\n b;\n}");
}); });
it("properly handles more than one arguments", function() { it("properly handles more than one arguments", function() {
@ -60,9 +59,9 @@ describe("modification", function() {
traverse(ast, { traverse(ast, {
CallExpression: function(path) { CallExpression: function(path) {
path.unshiftContainer("arguments", t.identifier("d")); path.unshiftContainer("arguments", t.identifier("d"));
assert.equal(generateCode(path), "foo(d, a, b);"); expect(generateCode(path)).toBe("foo(d, a, b);");
path.unshiftContainer("arguments", t.stringLiteral("s")); path.unshiftContainer("arguments", t.stringLiteral("s"));
assert.equal(generateCode(path), `foo("s", d, a, b);`); expect(generateCode(path)).toBe(`foo("s", d, a, b);`);
}, },
}); });
}); });
@ -74,10 +73,10 @@ describe("modification", function() {
const path = rootPath.get("consequent.body.0"); const path = rootPath.get("consequent.body.0");
const result = path.insertBefore(t.identifier("b")); const result = path.insertBefore(t.identifier("b"));
assert.equal(Array.isArray(result), true); expect(Array.isArray(result)).toBe(true);
assert.equal(result.length, 1); expect(result).toHaveLength(1);
assert.deepEqual(result[0].node, t.identifier("b")); expect(result[0].node).toEqual(t.identifier("b"));
assert.equal(generateCode(rootPath), "if (x) {\n b\n y;\n}"); expect(generateCode(rootPath)).toBe("if (x) {\n b\n y;\n}");
}); });
it("returns inserted path without BlockStatement", function() { it("returns inserted path without BlockStatement", function() {
@ -85,10 +84,10 @@ describe("modification", function() {
const path = rootPath.get("consequent"); const path = rootPath.get("consequent");
const result = path.insertBefore(t.identifier("b")); const result = path.insertBefore(t.identifier("b"));
assert.equal(Array.isArray(result), true); expect(Array.isArray(result)).toBe(true);
assert.equal(result.length, 1); expect(result).toHaveLength(1);
assert.deepEqual(result[0].node, t.identifier("b")); expect(result[0].node).toEqual(t.identifier("b"));
assert.equal(generateCode(rootPath), "if (x) {\n b\n y;\n}"); expect(generateCode(rootPath)).toBe("if (x) {\n b\n y;\n}");
}); });
it("returns inserted path without BlockStatement without ExpressionStatement", function() { it("returns inserted path without BlockStatement without ExpressionStatement", function() {
@ -96,11 +95,10 @@ describe("modification", function() {
const path = rootPath.get("consequent"); const path = rootPath.get("consequent");
const result = path.insertBefore(t.identifier("b")); const result = path.insertBefore(t.identifier("b"));
assert.equal(Array.isArray(result), true); expect(Array.isArray(result)).toBe(true);
assert.equal(result.length, 1); expect(result).toHaveLength(1);
assert.deepEqual(result[result.length - 1].node, t.identifier("b")); expect(result[result.length - 1].node).toEqual(t.identifier("b"));
assert.equal( expect(generateCode(rootPath)).toBe(
generateCode(rootPath),
"if (x) {\n b\n\n for (var i = 0; i < 0; i++) {}\n}", "if (x) {\n b\n\n for (var i = 0; i < 0; i++) {}\n}",
); );
}); });
@ -110,11 +108,10 @@ describe("modification", function() {
const path = rootPath.get("consequent.body.0"); const path = rootPath.get("consequent.body.0");
const result = path.insertBefore(t.identifier("b")); const result = path.insertBefore(t.identifier("b"));
assert.equal(Array.isArray(result), true); expect(Array.isArray(result)).toBe(true);
assert.equal(result.length, 1); expect(result).toHaveLength(1);
assert.deepEqual(result[result.length - 1].node, t.identifier("b")); expect(result[result.length - 1].node).toEqual(t.identifier("b"));
assert.equal( expect(generateCode(rootPath)).toBe(
generateCode(rootPath),
"if (x) {\n b\n\n for (var i = 0; i < 0; i++) {}\n}", "if (x) {\n b\n\n for (var i = 0; i < 0; i++) {}\n}",
); );
}); });
@ -127,8 +124,8 @@ describe("modification", function() {
const fnPath = bodyPath.get("body.0.declaration"); const fnPath = bodyPath.get("body.0.declaration");
fnPath.insertBefore(t.identifier("x")); fnPath.insertBefore(t.identifier("x"));
assert.equal(bodyPath.get("body").length, 2); expect(bodyPath.get("body")).toHaveLength(2);
assert.deepEqual(bodyPath.get("body.0").node, t.identifier("x")); expect(bodyPath.get("body.0").node).toEqual(t.identifier("x"));
}); });
it("the ExportDefaultDeclaration, if a declaration is exported", function() { it("the ExportDefaultDeclaration, if a declaration is exported", function() {
@ -138,8 +135,8 @@ describe("modification", function() {
const fnPath = bodyPath.get("body.0.declaration"); const fnPath = bodyPath.get("body.0.declaration");
fnPath.insertBefore(t.identifier("x")); fnPath.insertBefore(t.identifier("x"));
assert.equal(bodyPath.get("body").length, 2); expect(bodyPath.get("body")).toHaveLength(2);
assert.deepEqual(bodyPath.get("body.0").node, t.identifier("x")); expect(bodyPath.get("body.0").node).toEqual(t.identifier("x"));
}); });
it("the exported expression", function() { it("the exported expression", function() {
@ -149,7 +146,7 @@ describe("modification", function() {
const path = declPath.get("declaration"); const path = declPath.get("declaration");
path.insertBefore(t.identifier("x")); path.insertBefore(t.identifier("x"));
assert.equal(generateCode(declPath), "export default (x, 2);"); expect(generateCode(declPath)).toBe("export default (x, 2);");
}); });
}); });
}); });
@ -160,10 +157,10 @@ describe("modification", function() {
const path = rootPath.get("consequent.body.0"); const path = rootPath.get("consequent.body.0");
const result = path.insertAfter(t.identifier("b")); const result = path.insertAfter(t.identifier("b"));
assert.equal(Array.isArray(result), true); expect(Array.isArray(result)).toBe(true);
assert.equal(result.length, 1); expect(result).toHaveLength(1);
assert.deepEqual(result[result.length - 1].node, t.identifier("b")); expect(result[result.length - 1].node).toEqual(t.identifier("b"));
assert.equal(generateCode(rootPath), "if (x) {\n y;\n b\n}"); expect(generateCode(rootPath)).toBe("if (x) {\n y;\n b\n}");
}); });
it("returns inserted path without BlockStatement with ExpressionStatement", function() { it("returns inserted path without BlockStatement with ExpressionStatement", function() {
@ -171,10 +168,10 @@ describe("modification", function() {
const path = rootPath.get("consequent"); const path = rootPath.get("consequent");
const result = path.insertAfter(t.identifier("b")); const result = path.insertAfter(t.identifier("b"));
assert.equal(Array.isArray(result), true); expect(Array.isArray(result)).toBe(true);
assert.equal(result.length, 1); expect(result).toHaveLength(1);
assert.deepEqual(result[result.length - 1].node, t.identifier("b")); expect(result[result.length - 1].node).toEqual(t.identifier("b"));
assert.equal(generateCode(rootPath), "if (x) {\n y;\n b\n}"); expect(generateCode(rootPath)).toBe("if (x) {\n y;\n b\n}");
}); });
it("returns inserted path without BlockStatement without ExpressionStatement", function() { it("returns inserted path without BlockStatement without ExpressionStatement", function() {
@ -182,11 +179,10 @@ describe("modification", function() {
const path = rootPath.get("consequent"); const path = rootPath.get("consequent");
const result = path.insertAfter(t.identifier("b")); const result = path.insertAfter(t.identifier("b"));
assert.equal(Array.isArray(result), true); expect(Array.isArray(result)).toBe(true);
assert.equal(result.length, 1); expect(result).toHaveLength(1);
assert.deepEqual(result[result.length - 1].node, t.identifier("b")); expect(result[result.length - 1].node).toEqual(t.identifier("b"));
assert.equal( expect(generateCode(rootPath)).toBe(
generateCode(rootPath),
"if (x) {\n for (var i = 0; i < 0; i++) {}\n\n b\n}", "if (x) {\n for (var i = 0; i < 0; i++) {}\n\n b\n}",
); );
}); });
@ -196,11 +192,10 @@ describe("modification", function() {
const path = rootPath.get("consequent.body.0"); const path = rootPath.get("consequent.body.0");
const result = path.insertAfter(t.identifier("b")); const result = path.insertAfter(t.identifier("b"));
assert.equal(Array.isArray(result), true); expect(Array.isArray(result)).toBe(true);
assert.equal(result.length, 1); expect(result).toHaveLength(1);
assert.deepEqual(result[result.length - 1].node, t.identifier("b")); expect(result[result.length - 1].node).toEqual(t.identifier("b"));
assert.equal( expect(generateCode(rootPath)).toBe(
generateCode(rootPath),
"if (x) {\n for (var i = 0; i < 0; i++) {}\n\n b\n}", "if (x) {\n for (var i = 0; i < 0; i++) {}\n\n b\n}",
); );
}); });
@ -213,8 +208,8 @@ describe("modification", function() {
const fnPath = bodyPath.get("body.0.declaration"); const fnPath = bodyPath.get("body.0.declaration");
fnPath.insertAfter(t.identifier("x")); fnPath.insertAfter(t.identifier("x"));
assert.equal(bodyPath.get("body").length, 2); expect(bodyPath.get("body")).toHaveLength(2);
assert.deepEqual(bodyPath.get("body.1").node, t.identifier("x")); expect(bodyPath.get("body.1").node).toEqual(t.identifier("x"));
}); });
it("the ExportDefaultDeclaration, if a declaration is exported", function() { it("the ExportDefaultDeclaration, if a declaration is exported", function() {
@ -224,8 +219,8 @@ describe("modification", function() {
const fnPath = bodyPath.get("body.0.declaration"); const fnPath = bodyPath.get("body.0.declaration");
fnPath.insertAfter(t.identifier("x")); fnPath.insertAfter(t.identifier("x"));
assert.equal(bodyPath.get("body").length, 2); expect(bodyPath.get("body")).toHaveLength(2);
assert.deepEqual(bodyPath.get("body.1").node, t.identifier("x")); expect(bodyPath.get("body.1").node).toEqual(t.identifier("x"));
}); });
it("the exported expression", function() { it("the exported expression", function() {
@ -235,8 +230,7 @@ describe("modification", function() {
const path = bodyPath.get("body.0.declaration"); const path = bodyPath.get("body.0.declaration");
path.insertAfter(t.identifier("x")); path.insertAfter(t.identifier("x"));
assert.equal( expect(generateCode({ parentPath: bodyPath })).toBe(
generateCode({ parentPath: bodyPath }),
"var _temp;\n\nexport default (_temp = 2, x, _temp);", "var _temp;\n\nexport default (_temp = 2, x, _temp);",
); );
}); });

View File

@ -1,5 +1,4 @@
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
import generate from "@babel/generator"; import generate from "@babel/generator";
@ -31,11 +30,7 @@ describe("removal", function() {
const body = path.get("body"); const body = path.get("body");
body.remove(); body.remove();
assert.equal( expect(generateCode(rootPath)).toBe("x = () => {};");
generateCode(rootPath),
"x = () => {};",
"body should be replaced with BlockStatement",
);
}); });
}); });
}); });

View File

@ -1,5 +1,4 @@
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
import * as t from "@babel/types"; import * as t from "@babel/types";
@ -25,7 +24,7 @@ describe("path/replacement", function() {
}, },
}); });
assert(ast.program.body[0].declaration.type == "ArrayExpression"); expect(ast.program.body[0].declaration.type).toBe("ArrayExpression");
}); });
it("throws error when trying to replace Program with a non-Program node", function() { it("throws error when trying to replace Program with a non-Program node", function() {

View File

@ -1,5 +1,4 @@
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
function getPath(code, options) { function getPath(code, options) {
@ -30,155 +29,139 @@ function getIdentifierPath(code) {
describe("scope", function() { describe("scope", function() {
describe("binding paths", function() { describe("binding paths", function() {
it("function declaration id", function() { it("function declaration id", function() {
assert.ok( expect(
getPath("function foo() {}").scope.getBinding("foo").path.type === getPath("function foo() {}").scope.getBinding("foo").path.type,
"FunctionDeclaration", ).toBe("FunctionDeclaration");
);
}); });
it("function expression id", function() { it("function expression id", function() {
assert.ok( expect(
getPath("(function foo() {})") getPath("(function foo() {})")
.get("body")[0] .get("body")[0]
.get("expression") .get("expression")
.scope.getBinding("foo").path.type === "FunctionExpression", .scope.getBinding("foo").path.type,
); ).toBe("FunctionExpression");
}); });
it("function param", function() { it("function param", function() {
assert.ok( expect(
getPath("(function (foo) {})") getPath("(function (foo) {})")
.get("body")[0] .get("body")[0]
.get("expression") .get("expression")
.scope.getBinding("foo").path.type === "Identifier", .scope.getBinding("foo").path.type,
); ).toBe("Identifier");
}); });
it("variable declaration", function() { it("variable declaration", function() {
assert.ok( expect(getPath("var foo = null;").scope.getBinding("foo").path.type).toBe(
getPath("var foo = null;").scope.getBinding("foo").path.type ===
"VariableDeclarator", "VariableDeclarator",
); );
assert.ok( expect(
getPath("var { foo } = null;").scope.getBinding("foo").path.type === getPath("var { foo } = null;").scope.getBinding("foo").path.type,
"VariableDeclarator", ).toBe("VariableDeclarator");
); expect(
assert.ok( getPath("var [ foo ] = null;").scope.getBinding("foo").path.type,
getPath("var [ foo ] = null;").scope.getBinding("foo").path.type === ).toBe("VariableDeclarator");
"VariableDeclarator", expect(
);
assert.ok(
getPath("var { bar: [ foo ] } = null;").scope.getBinding("foo").path getPath("var { bar: [ foo ] } = null;").scope.getBinding("foo").path
.type === "VariableDeclarator", .type,
); ).toBe("VariableDeclarator");
}); });
it("declare var", function() { it("declare var", function() {
assert.equal( expect(
getPath("declare var foo;", { plugins: ["flow"] }).scope.getBinding( getPath("declare var foo;", { plugins: ["flow"] }).scope.getBinding(
"foo", "foo",
), ),
null, ).toBeUndefined();
);
}); });
it("declare function", function() { it("declare function", function() {
assert.equal( expect(
getPath("declare function foo(): void;", { getPath("declare function foo(): void;", {
plugins: ["flow"], plugins: ["flow"],
}).scope.getBinding("foo"), }).scope.getBinding("foo"),
null, ).toBeUndefined();
);
}); });
it("variable constantness", function() { it("variable constantness", function() {
assert.ok(getPath("var a = 1;").scope.getBinding("a").constant === true); expect(getPath("var a = 1;").scope.getBinding("a").constant).toBe(true);
assert.ok( expect(getPath("var a = 1; a = 2;").scope.getBinding("a").constant).toBe(
getPath("var a = 1; a = 2;").scope.getBinding("a").constant === false,
);
assert.ok(
getPath("var a = 1, a = 2;").scope.getBinding("a").constant === false,
);
assert.ok(
getPath("var a = 1; var a = 2;").scope.getBinding("a").constant ===
false, false,
); );
expect(getPath("var a = 1, a = 2;").scope.getBinding("a").constant).toBe(
false,
);
expect(
getPath("var a = 1; var a = 2;").scope.getBinding("a").constant,
).toBe(false);
}); });
it("purity", function() { it("purity", function() {
assert.ok( expect(
getPath("({ x: 1 })") getPath("({ x: 1 })")
.get("body")[0] .get("body")[0]
.get("expression") .get("expression")
.isPure(), .isPure(),
); ).toBeTruthy();
assert.ok( expect(
!getPath("`${a}`") getPath("`${a}`")
.get("body")[0] .get("body")[0]
.get("expression") .get("expression")
.isPure(), .isPure(),
); ).toBeFalsy();
assert.ok( expect(
getPath("let a = 1; `${a}`") getPath("let a = 1; `${a}`")
.get("body")[1] .get("body")[1]
.get("expression") .get("expression")
.isPure(), .isPure(),
); ).toBeTruthy();
assert.ok( expect(
!getPath("let a = 1; `${a++}`") getPath("let a = 1; `${a++}`")
.get("body")[1] .get("body")[1]
.get("expression") .get("expression")
.isPure(), .isPure(),
); ).toBeFalsy();
assert.ok( expect(
!getPath("tagged`foo`") getPath("tagged`foo`")
.get("body")[0] .get("body")[0]
.get("expression") .get("expression")
.isPure(), .isPure(),
); ).toBeFalsy();
assert.ok( expect(
getPath("String.raw`foo`") getPath("String.raw`foo`")
.get("body")[0] .get("body")[0]
.get("expression") .get("expression")
.isPure(), .isPure(),
); ).toBeTruthy();
}); });
test("label", function() { test("label", function() {
assert.strictEqual( expect(getPath("foo: { }").scope.getBinding("foo")).toBeUndefined();
getPath("foo: { }").scope.getBinding("foo"), expect(getPath("foo: { }").scope.getLabel("foo").type).toBe(
undefined,
);
assert.strictEqual(
getPath("foo: { }").scope.getLabel("foo").type,
"LabeledStatement", "LabeledStatement",
); );
assert.strictEqual( expect(getPath("foo: { }").scope.getLabel("toString")).toBeUndefined();
getPath("foo: { }").scope.getLabel("toString"),
undefined,
);
assert.strictEqual( expect(
getPath( getPath(
` `
foo: { } foo: { }
`, `,
).scope.generateUid("foo"), ).scope.generateUid("foo"),
"_foo", ).toBe("_foo");
);
}); });
test("generateUid collision check with labels", function() { test("generateUid collision check with labels", function() {
assert.strictEqual( expect(
getPath( getPath(
` `
_foo: { } _foo: { }
`, `,
).scope.generateUid("foo"), ).scope.generateUid("foo"),
"_foo2", ).toBe("_foo2");
);
assert.strictEqual( expect(
getPath( getPath(
` `
_foo: { } _foo: { }
@ -186,19 +169,18 @@ describe("scope", function() {
_foo2: { } _foo2: { }
`, `,
).scope.generateUid("foo"), ).scope.generateUid("foo"),
"_foo3", ).toBe("_foo3");
);
}); });
it("reference paths", function() { it("reference paths", function() {
const path = getIdentifierPath("function square(n) { return n * n}"); const path = getIdentifierPath("function square(n) { return n * n}");
const referencePaths = path.context.scope.bindings.n.referencePaths; const referencePaths = path.context.scope.bindings.n.referencePaths;
assert.equal(referencePaths.length, 2); expect(referencePaths).toHaveLength(2);
assert.deepEqual(referencePaths[0].node.loc.start, { expect(referencePaths[0].node.loc.start).toEqual({
line: 1, line: 1,
column: 28, column: 28,
}); });
assert.deepEqual(referencePaths[1].node.loc.start, { expect(referencePaths[1].node.loc.start).toEqual({
line: 1, line: 1,
column: 32, column: 32,
}); });

View File

@ -1,6 +1,5 @@
import cloneDeep from "lodash/cloneDeep"; import cloneDeep from "lodash/cloneDeep";
import traverse from "../lib"; import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
describe("traverse", function() { describe("traverse", function() {
@ -25,11 +24,11 @@ describe("traverse", function() {
}, },
}); });
assert.equal(ast2.body[1].expression.left.object, replacement); expect(ast2.body[1].expression.left.object).toBe(replacement);
}); });
it("traverse", function() { it("traverse", function() {
const expect = [ const expected = [
body[0], body[0],
body[0].declarations[0], body[0].declarations[0],
body[0].declarations[0].id, body[0].declarations[0].id,
@ -50,7 +49,7 @@ describe("traverse", function() {
}, },
}); });
assert.deepEqual(actual, expect); expect(actual).toEqual(expected);
}); });
it("traverse falsy parent", function() { it("traverse falsy parent", function() {
@ -62,7 +61,7 @@ describe("traverse", function() {
}); });
it("traverse blacklistTypes", function() { it("traverse blacklistTypes", function() {
const expect = [ const expected = [
body[0], body[0],
body[0].declarations[0], body[0].declarations[0],
body[0].declarations[0].id, body[0].declarations[0].id,
@ -81,22 +80,24 @@ describe("traverse", function() {
}, },
}); });
assert.deepEqual(actual, expect); expect(actual).toEqual(expected);
}); });
it("hasType", function() { it("hasType", function() {
assert.ok(traverse.hasType(ast, "ThisExpression")); expect(traverse.hasType(ast, "ThisExpression")).toBeTruthy();
assert.ok( expect(
!traverse.hasType(ast, "ThisExpression", ["AssignmentExpression"]), traverse.hasType(ast, "ThisExpression", ["AssignmentExpression"]),
); ).toBeFalsy();
assert.ok(traverse.hasType(ast, "ThisExpression")); expect(traverse.hasType(ast, "ThisExpression")).toBeTruthy();
assert.ok(traverse.hasType(ast, "Program")); expect(traverse.hasType(ast, "Program")).toBeTruthy();
assert.ok(!traverse.hasType(ast, "ThisExpression", ["MemberExpression"])); expect(
assert.ok(!traverse.hasType(ast, "ThisExpression", ["Program"])); traverse.hasType(ast, "ThisExpression", ["MemberExpression"]),
).toBeFalsy();
expect(traverse.hasType(ast, "ThisExpression", ["Program"])).toBeFalsy();
assert.ok(!traverse.hasType(ast, "ArrowFunctionExpression")); expect(traverse.hasType(ast, "ArrowFunctionExpression")).toBeFalsy();
}); });
it("clearCache", function() { it("clearCache", function() {
@ -123,8 +124,8 @@ describe("traverse", function() {
}); });
scopes2.forEach(function(_, i) { scopes2.forEach(function(_, i) {
assert.notStrictEqual(scopes[i], scopes2[i]); expect(scopes[i]).not.toBe(scopes2[i]);
assert.notStrictEqual(paths[i], paths2[i]); expect(paths[i]).not.toBe(paths2[i]);
}); });
}); });
@ -146,7 +147,7 @@ describe("traverse", function() {
}); });
paths2.forEach(function(p, i) { paths2.forEach(function(p, i) {
assert.notStrictEqual(p, paths[i]); expect(p).not.toBe(paths[i]);
}); });
}); });
@ -170,7 +171,7 @@ describe("traverse", function() {
}); });
scopes2.forEach(function(p, i) { scopes2.forEach(function(p, i) {
assert.notStrictEqual(p, scopes[i]); expect(p).not.toBe(scopes[i]);
}); });
}); });
}); });

View File

@ -1,5 +1,4 @@
import * as t from "../lib"; import * as t from "../lib";
import assert from "assert";
describe("asserts", () => { describe("asserts", () => {
const consoleTrace = console.trace; const consoleTrace = console.trace;
@ -17,17 +16,10 @@ describe("asserts", () => {
const nodeType = k.replace("assert", ""); const nodeType = k.replace("assert", "");
it(nodeType, () => { it(nodeType, () => {
assert.throws( expect(() => {
() => {
t[k]({ type: "FlavorTownDeclaration" }, {}); t[k]({ type: "FlavorTownDeclaration" }, {});
}, }).toThrow(
err => { `Expected type "${nodeType}" with option {}, but instead got "FlavorTownDeclaration".`,
return (
err instanceof Error &&
err.message ===
`Expected type "${nodeType}" with option {}, but instead got "FlavorTownDeclaration".`
);
},
); );
}); });
} }

View File

@ -1,62 +1,59 @@
import * as t from "../lib"; import * as t from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
describe("cloneNode", function() { describe("cloneNode", function() {
it("should handle undefined", function() { it("should handle undefined", function() {
const node = undefined; const node = undefined;
const cloned = t.cloneNode(node); const cloned = t.cloneNode(node);
assert(cloned === undefined); expect(cloned).toBeUndefined();
}); });
it("should handle null", function() { it("should handle null", function() {
const node = null; const node = null;
const cloned = t.cloneNode(node); const cloned = t.cloneNode(node);
assert(cloned === null); expect(cloned).toBeNull();
}); });
it("should handle simple cases", function() { it("should handle simple cases", function() {
const node = t.identifier("a"); const node = t.identifier("a");
const cloned = t.cloneNode(node); const cloned = t.cloneNode(node);
assert(node !== cloned); expect(node).not.toBe(cloned);
assert(t.isNodesEquivalent(node, cloned) === true); expect(t.isNodesEquivalent(node, cloned)).toBe(true);
}); });
it("should handle full programs", function() { it("should handle full programs", function() {
const file = parse("1 + 1"); const file = parse("1 + 1");
const cloned = t.cloneNode(file); const cloned = t.cloneNode(file);
assert(file !== cloned); expect(file).not.toBe(cloned);
assert( expect(file.program.body[0].expression.right).not.toBe(
file.program.body[0].expression.right !==
cloned.program.body[0].expression.right, cloned.program.body[0].expression.right,
); );
assert( expect(file.program.body[0].expression.left).not.toBe(
file.program.body[0].expression.left !==
cloned.program.body[0].expression.left, cloned.program.body[0].expression.left,
); );
assert(t.isNodesEquivalent(file, cloned) === true); expect(t.isNodesEquivalent(file, cloned)).toBe(true);
}); });
it("should handle complex programs", function() { it("should handle complex programs", function() {
const program = "'use strict'; function lol() { wow();return 1; }"; const program = "'use strict'; function lol() { wow();return 1; }";
const node = parse(program); const node = parse(program);
const cloned = t.cloneNode(node); const cloned = t.cloneNode(node);
assert(node !== cloned); expect(node).not.toBe(cloned);
assert(t.isNodesEquivalent(node, cloned) === true); expect(t.isNodesEquivalent(node, cloned)).toBe(true);
}); });
it("should handle missing array element", function() { it("should handle missing array element", function() {
const node = parse("[,0]"); const node = parse("[,0]");
const cloned = t.cloneNode(node); const cloned = t.cloneNode(node);
assert(node !== cloned); expect(node).not.toBe(cloned);
assert(t.isNodesEquivalent(node, cloned) === true); expect(t.isNodesEquivalent(node, cloned)).toBe(true);
}); });
it("should support shallow cloning", function() { it("should support shallow cloning", function() {
const node = t.memberExpression(t.identifier("foo"), t.identifier("bar")); const node = t.memberExpression(t.identifier("foo"), t.identifier("bar"));
const cloned = t.cloneNode(node, /* deep */ false); const cloned = t.cloneNode(node, /* deep */ false);
assert.notStrictEqual(node, cloned); expect(node).not.toBe(cloned);
assert.strictEqual(node.object, cloned.object); expect(node.object).toBe(cloned.object);
assert.strictEqual(node.property, cloned.property); expect(node.property).toBe(cloned.property);
}); });
}); });

View File

@ -1,5 +1,4 @@
import * as t from "../lib"; import * as t from "../lib";
import { assert } from "chai";
import { parse } from "babylon"; import { parse } from "babylon";
function parseCode(string) { function parseCode(string) {
@ -12,34 +11,34 @@ describe("misc helpers", function() {
describe("matchesPattern", function() { describe("matchesPattern", function() {
it("matches explicitly", function() { it("matches explicitly", function() {
const ast = parseCode("a.b.c.d").expression; const ast = parseCode("a.b.c.d").expression;
assert(t.matchesPattern(ast, "a.b.c.d")); expect(t.matchesPattern(ast, "a.b.c.d")).toBeTruthy();
assert.isFalse(t.matchesPattern(ast, "a.b.c")); expect(t.matchesPattern(ast, "a.b.c")).toBe(false);
assert.isFalse(t.matchesPattern(ast, "b.c.d")); expect(t.matchesPattern(ast, "b.c.d")).toBe(false);
assert.isFalse(t.matchesPattern(ast, "a.b.c.d.e")); expect(t.matchesPattern(ast, "a.b.c.d.e")).toBe(false);
}); });
it("matches partially", function() { it("matches partially", function() {
const ast = parseCode("a.b.c.d").expression; const ast = parseCode("a.b.c.d").expression;
assert(t.matchesPattern(ast, "a.b.c.d", true)); expect(t.matchesPattern(ast, "a.b.c.d", true)).toBeTruthy();
assert(t.matchesPattern(ast, "a.b.c", true)); expect(t.matchesPattern(ast, "a.b.c", true)).toBeTruthy();
assert.isFalse(t.matchesPattern(ast, "b.c.d", true)); expect(t.matchesPattern(ast, "b.c.d", true)).toBe(false);
assert.isFalse(t.matchesPattern(ast, "a.b.c.d.e", true)); expect(t.matchesPattern(ast, "a.b.c.d.e", true)).toBe(false);
}); });
it("matches string literal expressions", function() { it("matches string literal expressions", function() {
const ast = parseCode("a['b'].c.d").expression; const ast = parseCode("a['b'].c.d").expression;
assert(t.matchesPattern(ast, "a.b.c.d")); expect(t.matchesPattern(ast, "a.b.c.d")).toBeTruthy();
assert.isFalse(t.matchesPattern(ast, "a.b.c")); expect(t.matchesPattern(ast, "a.b.c")).toBe(false);
assert.isFalse(t.matchesPattern(ast, "b.c.d")); expect(t.matchesPattern(ast, "b.c.d")).toBe(false);
assert.isFalse(t.matchesPattern(ast, "a.b.c.d.e")); expect(t.matchesPattern(ast, "a.b.c.d.e")).toBe(false);
}); });
it("matches string literal expressions partially", function() { it("matches string literal expressions partially", function() {
const ast = parseCode("a['b'].c.d").expression; const ast = parseCode("a['b'].c.d").expression;
assert(t.matchesPattern(ast, "a.b.c.d", true)); expect(t.matchesPattern(ast, "a.b.c.d", true)).toBeTruthy();
assert(t.matchesPattern(ast, "a.b.c", true)); expect(t.matchesPattern(ast, "a.b.c", true)).toBeTruthy();
assert.isFalse(t.matchesPattern(ast, "b.c.d", true)); expect(t.matchesPattern(ast, "b.c.d", true)).toBe(false);
assert.isFalse(t.matchesPattern(ast, "a.b.c.d.e", true)); expect(t.matchesPattern(ast, "a.b.c.d.e", true)).toBe(false);
}); });
}); });
}); });

View File

@ -1,5 +1,4 @@
import * as t from "../lib"; import * as t from "../lib";
import assert from "assert";
import { parse } from "babylon"; import { parse } from "babylon";
function getBody(program) { function getBody(program) {
@ -11,17 +10,17 @@ describe("retrievers", function() {
it("variable declarations", function() { it("variable declarations", function() {
const program = "var a = 1; let b = 2; const c = 3;"; const program = "var a = 1; let b = 2; const c = 3;";
const ids = t.getBindingIdentifiers(getBody(program)); const ids = t.getBindingIdentifiers(getBody(program));
assert.deepEqual(Object.keys(ids), ["a", "b", "c"]); expect(Object.keys(ids)).toEqual(["a", "b", "c"]);
}); });
it("function declarations", function() { it("function declarations", function() {
const program = "var foo = 1; function bar() { var baz = 2; }"; const program = "var foo = 1; function bar() { var baz = 2; }";
const ids = t.getBindingIdentifiers(getBody(program)); const ids = t.getBindingIdentifiers(getBody(program));
assert.deepEqual(Object.keys(ids), ["bar", "foo"]); expect(Object.keys(ids)).toEqual(["bar", "foo"]);
}); });
it("export named declarations", function() { it("export named declarations", function() {
const program = "export const foo = 'foo';"; const program = "export const foo = 'foo';";
const ids = t.getBindingIdentifiers(getBody(program)); const ids = t.getBindingIdentifiers(getBody(program));
assert.deepEqual(Object.keys(ids), ["foo"]); expect(Object.keys(ids)).toEqual(["foo"]);
}); });
}); });
}); });