Migrate to jest (#7455)

This commit is contained in:
Daniel Tschinder 2018-03-03 10:58:19 +01:00 committed by GitHub
parent 53208d6998
commit 3e95830646
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 1861 additions and 1133 deletions

View File

@ -1,9 +1,20 @@
"use strict";
let envOpts = {
const env = process.env.BABEL_ENV || process.env.NODE_ENV;
const envOpts = {
loose: true,
};
switch(env) {
case "development":
envOpts.debug = true;
// fall-through
case "test":
envOpts.targets = {
node: "current"
};
}
const config = {
comments: false,
presets: [["@babel/env", envOpts]],
@ -27,16 +38,10 @@ const config = {
],
};
// we need to do this as long as we do not test everything from source
if (process.env.BABEL_ENV === "cov") {
config.auxiliaryCommentBefore = "istanbul ignore next";
config.plugins.push("babel-plugin-istanbul");
}
if (process.env.BABEL_ENV === "development") {
envOpts.targets = {
node: "current",
};
envOpts.debug = true;
}
module.exports = config;

View File

@ -51,8 +51,8 @@ jobs:
# test-ci-coverage doesn't test babel-standalone, as trying to gather coverage
# data for a JS file that's several megabytes large is bound to fail. Here,
# we just run the babel-standalone test separately.
- run: ./node_modules/mocha/bin/_mocha packages/babel-standalone/test/ --opts test/mocha.opts
- run: ./node_modules/mocha/bin/_mocha packages/babel-preset-env-standalone/test/ --opts test/mocha.opts
- run: ./node_modules/.bin/jest packages/babel-standalone/test/
- run: ./node_modules/.bin/jest packages/babel-preset-env-standalone/test/
- store_artifacts: *artifact_babel
- store_artifacts: *artifact_babel_min
- store_artifacts: *artifact_env

View File

@ -28,7 +28,7 @@
"test/**/*.js"
],
"env": {
"mocha": true
"jest": true
}
}
]

View File

@ -7,6 +7,7 @@ cache:
directories:
- node_modules
node_js:
- '9'
- '8'
- '6'
- '4'
@ -19,6 +20,8 @@ env:
before_install:
- curl -o- -L https://yarnpkg.com/install.sh | bash
install: yarn --ignore-engines
before_script:
- 'if [ "$JOB" = "babylon-flow-tests" ]; then make bootstrap-flow; fi'
- 'if [ "$JOB" = "babylon-test262-tests" ]; then make bootstrap-test262; fi'

View File

@ -81,7 +81,7 @@ test-ci:
test-ci-coverage: SHELL:=/bin/bash
test-ci-coverage:
BABEL_ENV=cov make bootstrap
./scripts/test-cov.sh
TEST_TYPE=cov ./scripts/test-cov.sh
bash <(curl -s https://codecov.io/bash) -f coverage/coverage-final.json
bootstrap-flow:
@ -130,8 +130,8 @@ publish:
bootstrap:
make clean-all
yarn
./node_modules/.bin/lerna bootstrap
yarn --ignore-engines
./node_modules/.bin/lerna bootstrap -- --ignore-engines
make build
cd packages/babel-runtime; \
node scripts/build-dist.js

View File

@ -16,9 +16,10 @@
"@babel/preset-flow": "7.0.0-beta.40",
"@babel/preset-stage-0": "7.0.0-beta.40",
"@babel/register": "7.0.0-beta.40",
"babel-core": "^7.0.0-0",
"babel-eslint": "^8.0.1",
"babel-jest": "^22.4.1",
"babel-loader": "8.0.0-beta.0",
"babel-plugin-istanbul": "^4.1.5",
"babel-plugin-transform-charcodes": "^0.1.0",
"babylon": "7.0.0-beta.40",
"browserify": "^13.1.1",
@ -44,13 +45,12 @@
"gulp-util": "^3.0.7",
"gulp-watch": "^4.3.5",
"husky": "^0.14.3",
"jest": "^22.4.2",
"lerna": "2.0.0",
"lerna-changelog": "^0.5.0",
"lint-staged": "^6.0.1",
"lodash": "^4.2.0",
"merge-stream": "^1.0.1",
"mocha": "^3.0.0",
"nyc": "^11.0.3",
"output-file-sync": "^2.0.0",
"prettier": "1.10.2",
"pump": "^1.0.2",
@ -71,20 +71,44 @@
"npm": ">= 2.x <= 5.x",
"yarn": ">=0.27.5 || >=1.0.0-20170811"
},
"nyc": {
"all": true,
"exclude": [
"scripts/*.js",
"packages/*/test/**",
"packages/babel-standalone/**",
"codemods/*/test/**"
],
"sourceMap": false,
"instrument": false
},
"lint-staged": {
"*.js": [
"eslint --format=codeframe --rulesdir='./scripts/eslint_rules'"
]
},
"jest": {
"collectCoverageFrom": [
"packages/*/src/**/*.js",
"codemods/*/src/**/*.js"
],
"testRegex": "./(packages|codemods)/[^/]+/test/.+\\.js$",
"testPathIgnorePatterns": [
"/node_modules/",
"/test/fixtures/",
"/test/debug-fixtures/",
"/babylon/test/expressions/",
"/test/tmp/",
"/test/__data__/",
"/test/helpers/",
"<rootDir>/test/warning.js",
"<rootDir>/build/",
"_browser.js"
],
"testEnvironment": "node",
"setupTestFrameworkScriptFile": "<rootDir>/test/testSetupFile.js",
"transformIgnorePatterns": [
"/node_modules/",
"/test/fixtures/",
"/test/tmp/",
"/test/__data__/",
"/lib/"
],
"modulePaths": [
"<rootDir>/packages/"
],
"modulePathIgnorePatterns": [
"/test/fixtures/",
"<rootDir>/build/"
]
}
}

View File

@ -122,7 +122,13 @@ const buildTest = function(binName, testName, opts) {
const binLoc = path.join(__dirname, "../lib", binName);
return function(callback) {
clear();
const dir = process.cwd();
process.chdir(__dirname);
if (fs.existsSync(tmpLoc)) rimraf.sync(tmpLoc);
fs.mkdirSync(tmpLoc);
process.chdir(tmpLoc);
saveInFiles(opts.inFiles);
let args = [binLoc];
@ -160,6 +166,7 @@ const buildTest = function(binName, testName, opts) {
args.map(arg => `"${arg}"`).join(" ") + ": " + err.message;
}
process.chdir(dir);
callback(err);
});
@ -170,13 +177,6 @@ const buildTest = function(binName, testName, opts) {
};
};
const clear = function() {
process.chdir(__dirname);
if (fs.existsSync(tmpLoc)) rimraf.sync(tmpLoc);
fs.mkdirSync(tmpLoc);
process.chdir(tmpLoc);
};
fs.readdirSync(fixtureLoc).forEach(function(binName) {
if (binName[0] === ".") return;

View File

@ -180,15 +180,17 @@ export default function(
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const deprecationError = new Error(
"Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.",
);
deprecationError.name = "DeprecationWarning";
const message =
"Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(deprecationError);
// A string is directly supplied to emitWarning, because when supplying an
// Error object node throws in the tests because of different contexts
process.emitWarning(message, "DeprecationWarning");
} else {
console.warn(deprecationError);
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}

View File

@ -299,6 +299,9 @@ describe("api", function() {
return { plugins: [pushPlugin(str)] };
}
const oldEnv = process.env.BABEL_ENV;
process.env.BABEL_ENV = "development";
const result = babel.transform("", {
filename: path.join(
__dirname,
@ -316,6 +319,12 @@ describe("api", function() {
},
});
if (oldEnv === undefined) {
delete process.env.BABEL_ENV;
} else {
process.env.BABEL_ENV = oldEnv;
}
assert.equal(
result.code,
[
@ -535,14 +544,14 @@ describe("api", function() {
const oldBabelEnv = process.env.BABEL_ENV;
const oldNodeEnv = process.env.NODE_ENV;
setup(function() {
beforeEach(function() {
// Tests need to run with the default and specific values for these. They
// need to be cleared for each test.
delete process.env.BABEL_ENV;
delete process.env.NODE_ENV;
});
suiteTeardown(function() {
afterAll(function() {
process.env.BABEL_ENV = oldBabelEnv;
process.env.NODE_ENV = oldNodeEnv;
});

View File

@ -844,6 +844,19 @@ describe("buildConfigChain", function() {
plugins: [],
presets: [],
});
const realEnv = process.env.NODE_ENV;
const realBabelEnv = process.env.BABEL_ENV;
beforeAll(() => {
delete process.env.NODE_ENV;
delete process.env.BABEL_ENV;
});
afterAll(() => {
if (realEnv) {
process.env.NODE_ENV = realEnv;
process.env.NODE_ENV = realBabelEnv;
}
});
it("should load .babelrc", () => {
const filename = fixture("config-files", "babelrc", "src.js");

View File

@ -4,14 +4,15 @@ import path from "path";
describe("addon resolution", function() {
const base = path.join(__dirname, "fixtures", "resolution");
let cwd;
beforeEach(function() {
this.cwd = process.cwd();
cwd = process.cwd();
process.chdir(base);
});
afterEach(function() {
process.chdir(this.cwd);
process.chdir(cwd);
});
it("should find module: presets", function() {

View File

@ -13,6 +13,7 @@
"@babel/helper-fixtures": "7.0.0-beta.40",
"@babel/polyfill": "7.0.0-beta.40",
"chai": "^4.1.0",
"jest": "^22.4.2",
"lodash": "^4.2.0",
"resolve": "^1.3.2",
"source-map": "^0.5.0"

View File

@ -1,4 +1,4 @@
/* eslint-env mocha */
/* eslint-env jest */
import * as babel from "@babel/core";
import { buildExternalHelpers } from "@babel/core";
import getFixtures from "@babel/helper-fixtures";
@ -11,7 +11,6 @@ import extend from "lodash/extend";
import merge from "lodash/merge";
import resolve from "resolve";
import assert from "assert";
import chai from "chai";
import fs from "fs";
import path from "path";
import vm from "vm";
@ -321,7 +320,7 @@ function checkDuplicatedNodes(ast) {
function run(task) {
const actual = task.actual;
const expect = task.expect;
const expected = task.expect;
const exec = task.exec;
const opts = task.options;
const optionsDir = task.optionsDir;
@ -376,29 +375,27 @@ function run(task) {
}
let actualCode = actual.code;
const expectCode = expect.code;
const expectCode = expected.code;
if (!execCode || actualCode) {
result = babel.transform(actualCode, getOpts(actual));
checkDuplicatedNodes(result.ast);
if (
!expect.code &&
!expected.code &&
result.code &&
!opts.throws &&
fs.statSync(path.dirname(expect.loc)).isDirectory() &&
fs.statSync(path.dirname(expected.loc)).isDirectory() &&
!process.env.CI
) {
console.log(`New test file created: ${expect.loc}`);
fs.writeFileSync(expect.loc, `${result.code}\n`);
console.log(`New test file created: ${expected.loc}`);
fs.writeFileSync(expected.loc, `${result.code}\n`);
} else {
actualCode = result.code.trim();
chai
.expect(actualCode)
.to.be.equal(expectCode, actual.loc + " !== " + expect.loc);
expect(actualCode).toEqual(expectCode);
}
}
if (task.sourceMap) {
chai.expect(result.map).to.deep.equal(task.sourceMap);
expect(result.map).toEqual(task.sourceMap);
}
if (task.sourceMappings) {
@ -407,10 +404,8 @@ function run(task) {
task.sourceMappings.forEach(function(mapping) {
const actual = mapping.original;
const expect = consumer.originalPositionFor(mapping.generated);
chai
.expect({ line: expect.line, column: expect.column })
.to.deep.equal(actual);
const expected = consumer.originalPositionFor(mapping.generated);
expect({ line: expected.line, column: expected.column }).toEqual(actual);
});
}

View File

@ -11,8 +11,7 @@
"devDependencies": {
"@babel/plugin-transform-new-target": "7.0.0-beta.40",
"@babel/preset-env": "7.0.0-beta.40",
"@babel/standalone": "7.0.0-beta.40",
"mock-require": "^2.0.2"
"@babel/standalone": "7.0.0-beta.40"
},
"keywords": [
"babel",

View File

@ -1,10 +1,14 @@
const assert = require("assert");
const mock = require("mock-require");
(process.env.TEST_TYPE === "cov" ? describe.skip : describe)(
"babel-preset-env-standalone",
() => {
const Babel = require("@babel/standalone/babel");
mock("Babel", Babel);
jest.mock("Babel", () => require("@babel/standalone/babel"), {
virtual: true,
});
require("../babel-preset-env");
describe("babel-preset-env-standalone", () => {
it("works w/o targets", () => {
const output = Babel.transform("const a = 1;", {
sourceType: "script",
@ -58,4 +62,5 @@ describe("babel-preset-env-standalone", () => {
"function Foo() {\n this instanceof Foo ? this.constructor : void 0;\n}",
);
});
});
},
);

View File

@ -1,5 +1,5 @@
import assert from "assert";
import getTargets from "../src/targets-parser";
import getTargets from "../lib/targets-parser";
describe("getTargets", () => {
it("parses", () => {

View File

@ -1,4 +1,3 @@
import { expect } from "chai";
import fs from "fs";
import path from "path";
@ -29,7 +28,7 @@ function resetCache() {
process.env.BABEL_DISABLE_CACHE = oldBabelDisableCacheValue;
}
describe("@babel/register - caching", () => {
describe.skip("@babel/register - caching", () => {
describe("cache", () => {
let load, get, save;
@ -44,22 +43,20 @@ describe("@babel/register - caching", () => {
});
afterEach(cleanCache);
after(resetCache);
afterAll(resetCache);
it("should load and get cached data", () => {
writeCache({ foo: "bar" });
load();
expect(get()).to.be.an("object");
expect(get()).to.deep.equal({ foo: "bar" });
expect(get()).toEqual({ foo: "bar" });
});
it("should load and get an object with no cached data", () => {
load();
expect(get()).to.be.an("object");
expect(get()).to.deep.equal({});
expect(get()).toEqual({});
});
it("should load and get an object with invalid cached data", () => {
@ -67,15 +64,14 @@ describe("@babel/register - caching", () => {
load();
expect(get()).to.be.an("object");
expect(get()).to.deep.equal({});
expect(get()).toEqual({});
});
it("should create the cache on save", () => {
save();
expect(fs.existsSync(testCacheFilename)).to.be.true;
expect(get()).to.deep.equal({});
expect(fs.existsSync(testCacheFilename)).toBe(true);
expect(get()).toEqual({});
});
});
});

View File

@ -1,10 +1,9 @@
import sourceMapSupport from "source-map-support";
import chai from "chai";
const DATA_ES2015 = require.resolve("./__data__/es2015");
const GEN_ERROR = require.resolve("./__data__/gen_error");
describe("@babel/register", function() {
describe.skip("@babel/register", function() {
let babelRegister;
let oldCompiler;
@ -36,7 +35,7 @@ describe("@babel/register", function() {
}
}
before(() => {
beforeAll(() => {
const js = require("default-require-extensions/js");
oldCompiler = require.extensions[".js"];
require.extensions[".js"] = js;
@ -45,7 +44,7 @@ describe("@babel/register", function() {
});
});
after(() => {
afterAll(() => {
require.extensions[".js"] = oldCompiler;
});
@ -58,22 +57,20 @@ describe("@babel/register", function() {
it("registers correctly", () => {
setupRegister();
chai.expect(require(DATA_ES2015)).to.be.ok;
expect(require(DATA_ES2015)).toBeTruthy();
});
it("reverts correctly", () => {
setupRegister();
chai.expect(require(DATA_ES2015)).to.be.ok;
expect(require(DATA_ES2015)).toBeTruthy();
delete require.cache[DATA_ES2015];
revertRegister();
chai
.expect(() => {
expect(() => {
require(DATA_ES2015);
})
.to.throw(SyntaxError);
}).toThrow(SyntaxError);
});
it("does not install source map support if asked not to", () => {
@ -82,16 +79,16 @@ describe("@babel/register", function() {
});
let gen_error;
chai.expect((gen_error = require(GEN_ERROR))).to.be.ok;
chai.expect(gen_error()).to.match(/gen_error\.js:8:34/);
expect((gen_error = require(GEN_ERROR))).toBeDefined();
expect(gen_error()).toEqual(/gen_error\.js:8:34/);
});
it("installs source map support by default", () => {
setupRegister();
let gen_error;
chai.expect((gen_error = require(GEN_ERROR))).to.be.ok;
chai.expect(gen_error()).to.match(/gen_error\.js:2:86/);
expect((gen_error = require(GEN_ERROR))).toBeDefined();
expect(gen_error()).toEqual(/gen_error\.js:2:86/);
});
it("installs source map support when requested", () => {
@ -100,7 +97,7 @@ describe("@babel/register", function() {
});
let gen_error;
chai.expect((gen_error = require(GEN_ERROR))).to.be.ok;
chai.expect(gen_error()).to.match(/gen_error\.js:2:86/);
expect((gen_error = require(GEN_ERROR))).toBeDefined();
expect(gen_error()).toEqual(/gen_error\.js:2:86/);
});
});

View File

@ -1,8 +1,11 @@
const assert = require("assert");
const Babel = require("../babel");
// Basic smoke tests for @babel/standalone
describe("@babel/standalone", () => {
(process.env.TEST_TYPE === "cov" ? describe.skip : describe)(
"@babel/standalone",
() => {
const Babel = require("../babel");
it("handles the es2015-no-commonjs preset", () => {
const output = Babel.transform('const getMessage = () => "Hello World"', {
presets: ["es2015-no-commonjs"],
@ -87,7 +90,9 @@ describe("@babel/standalone", () => {
// Transforms arrow syntax but NOT "const".
assert.equal(
output,
"const getMessage = function () {\n" + ' return "Hello World";\n' + "};",
"const getMessage = function () {\n" +
' return "Hello World";\n' +
"};",
);
});
@ -149,4 +154,5 @@ describe("@babel/standalone", () => {
);
});
});
});
},
);

View File

@ -2,7 +2,6 @@ import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon";
import * as t from "@babel/types";
import { expect } from "chai";
describe("path/replacement", function() {
describe("replaceWith", function() {
@ -37,7 +36,7 @@ describe("path/replacement", function() {
path.replaceWith(t.identifier("a"));
},
});
}).to.throw(
}).toThrow(
/You can only replace a Program root node with another Program node/,
);
});
@ -54,7 +53,7 @@ describe("path/replacement", function() {
]);
},
});
}).to.throw(
}).toThrow(
/Don't use `path\.replaceWith\(\)` with an array of nodes, use `path\.replaceWithMultiple\(\)`/,
);
});
@ -69,7 +68,7 @@ describe("path/replacement", function() {
path.replaceWith("17 + 23");
},
});
}).to.throw(
}).toThrow(
/Don't use `path\.replaceWith\(\)` with a source string, use `path\.replaceWithSourceString\(\)`/,
);
});
@ -83,7 +82,7 @@ describe("path/replacement", function() {
path.replaceWith(t.identifier("p"));
},
});
}).to.throw(/You can't replace this node, we've already removed it/);
}).toThrow(/You can't replace this node, we've already removed it/);
});
it("throws error when passed a falsy value", function() {
@ -94,7 +93,7 @@ describe("path/replacement", function() {
path.replaceWith();
},
});
}).to.throw(
}).toThrow(
/You passed `path\.replaceWith\(\)` a falsy node, use `path\.remove\(\)` instead/,
);
});

View File

@ -2,7 +2,7 @@ import * as t from "../lib";
import assert from "assert";
import { parse } from "babylon";
suite("cloneNode", function() {
describe("cloneNode", function() {
it("should handle undefined", function() {
const node = undefined;
const cloned = t.cloneNode(node);

View File

@ -1,5 +1,4 @@
import * as t from "../lib";
import { assert } from "chai";
import { parse } from "babylon";
import generate from "@babel/generator";
@ -14,49 +13,45 @@ function generateCode(node) {
describe("converters", function() {
it("toIdentifier", function() {
assert.equal(t.toIdentifier("swag-lord"), "swagLord");
expect(t.toIdentifier("swag-lord")).toBe("swagLord");
});
describe("valueToNode", function() {
it("number", function() {
assert.deepEqual(t.valueToNode(Math.PI), t.numericLiteral(Math.PI));
assert.deepEqual(t.valueToNode(-Infinity), t.numericLiteral(-Infinity));
assert.deepEqual(t.valueToNode(NaN), t.numericLiteral(NaN));
expect(t.valueToNode(Math.PI)).toEqual(t.numericLiteral(Math.PI));
expect(t.valueToNode(-Infinity)).toEqual(t.numericLiteral(-Infinity));
expect(t.valueToNode(NaN)).toEqual(t.numericLiteral(NaN));
});
it("string", function() {
assert.deepEqual(
t.valueToNode('This is a "string"'),
expect(t.valueToNode('This is a "string"')).toEqual(
t.stringLiteral('This is a "string"'),
);
});
it("boolean", function() {
assert.deepEqual(t.valueToNode(true), t.booleanLiteral(true));
assert.deepEqual(t.valueToNode(false), t.booleanLiteral(false));
expect(t.valueToNode(true)).toEqual(t.booleanLiteral(true));
expect(t.valueToNode(false)).toEqual(t.booleanLiteral(false));
});
it("null", function() {
assert.deepEqual(t.valueToNode(null), t.nullLiteral());
expect(t.valueToNode(null)).toEqual(t.nullLiteral());
});
it("undefined", function() {
assert.deepEqual(t.valueToNode(undefined), t.identifier("undefined"));
expect(t.valueToNode(undefined)).toEqual(t.identifier("undefined"));
});
it("RegExp", function() {
assert.deepEqual(
t.valueToNode(/abc.+/gm),
t.regExpLiteral("abc.+", "gm"),
);
expect(t.valueToNode(/abc.+/gm)).toEqual(t.regExpLiteral("abc.+", "gm"));
});
it("array", function() {
assert.deepEqual(
t.valueToNode([1, "a"]),
expect(t.valueToNode([1, "a"])).toEqual(
t.arrayExpression([t.numericLiteral(1), t.stringLiteral("a")]),
);
});
it("object", function() {
assert.deepEqual(
expect(
t.valueToNode({
a: 1,
"b c": 2,
}),
).toEqual(
t.objectExpression([
t.objectProperty(t.identifier("a"), t.numericLiteral(1)),
t.objectProperty(t.stringLiteral("b c"), t.numericLiteral(2)),
@ -64,12 +59,12 @@ describe("converters", function() {
);
});
it("throws if cannot convert", function() {
assert.throws(function() {
expect(function() {
t.valueToNode(Object);
});
assert.throws(function() {
}).toThrow();
expect(function() {
t.valueToNode(Symbol());
});
}).toThrow();
});
});
describe("toKeyAlias", function() {
@ -78,24 +73,22 @@ describe("converters", function() {
t.toKeyAlias.uid = 0;
});
it("doesn't change string literals", function() {
assert.equal(
expect(
t.toKeyAlias(t.objectProperty(t.stringLiteral("a"), t.nullLiteral())),
'"a"',
);
).toBe('"a"');
});
it("wraps around at Number.MAX_SAFE_INTEGER", function() {
assert.equal(
expect(
t.toKeyAlias(
t.objectMethod("method", t.identifier("a"), [], t.blockStatement([])),
),
"0",
);
).toBe("0");
});
});
describe("toStatement", function() {
it("noop on statements", function() {
const node = t.emptyStatement();
assert.equal(t.toStatement(node), node);
expect(t.toStatement(node)).toEqual(node);
t.assertEmptyStatement(node);
});
it("mutate class expression to declaration", function() {
@ -110,10 +103,10 @@ describe("converters", function() {
});
it("fail if class expression has no id", function() {
const node = t.classExpression(null, null, t.classBody([]), []);
assert.throws(function() {
expect(function() {
t.toStatement(node);
});
assert.strictEqual(t.toStatement(node, /* ignore = */ true), false);
}).toThrow(Error);
expect(t.toStatement(node, /* ignore = */ true)).toBe(false);
t.assertClassExpression(node);
});
it("mutate function expression to declaration", function() {
@ -127,10 +120,10 @@ describe("converters", function() {
});
it("fail if function expression has no id", function() {
const node = t.functionExpression(null, [], t.blockStatement([]));
assert.throws(function() {
expect(function() {
t.toStatement(node);
});
assert.strictEqual(t.toStatement(node, /* ignore = */ true), false);
}).toThrow(Error);
expect(t.toStatement(node, /* ignore = */ true)).toBe(false);
t.assertFunctionExpression(node);
});
it("assignment expression", function() {
@ -144,17 +137,17 @@ describe("converters", function() {
});
it("fail if cannot convert node type", function() {
const node = t.yieldExpression(t.identifier("foo"));
assert.throws(function() {
expect(function() {
t.toStatement(node);
});
assert.strictEqual(t.toStatement(node, /* ignore = */ true), false);
}).toThrow(Error);
expect(t.toStatement(node, /* ignore = */ true)).toBe(false);
t.assertYieldExpression(node);
});
});
describe("toExpression", function() {
it("noop on expressions", function() {
const node = t.identifier("a");
assert.equal(t.toExpression(node), node);
expect(t.toExpression(node)).toEqual(node);
t.assertIdentifier(node);
});
it("mutate class declaration to expression", function() {
@ -200,14 +193,14 @@ describe("converters", function() {
const inner = t.yieldExpression(t.identifier("foo"));
const node = t.expressionStatement(inner);
t.assertYieldExpression(t.toExpression(node));
assert.equal(t.toExpression(node), inner);
expect(t.toExpression(node)).toEqual(inner);
t.assertExpressionStatement(node);
});
it("fail if cannot convert node type", function() {
const node = t.program([]);
assert.throws(function() {
expect(function() {
t.toExpression(node);
});
}).toThrow(Error);
t.assertProgram(node);
});
});
@ -224,95 +217,94 @@ describe("converters", function() {
const node = t.identifier("a");
const sequence = t.toSequenceExpression([undefinedNode, node], scope);
t.assertSequenceExpression(sequence);
assert.equal(sequence.expressions[0], undefinedNode);
assert.equal(sequence.expressions[1], node);
expect(sequence.expressions[0]).toBe(undefinedNode);
expect(sequence.expressions[1]).toBe(node);
t.assertIdentifier(node);
});
it("avoids sequence for single node", function() {
const node = t.identifier("a");
let sequence = t.toSequenceExpression([node], scope);
assert.equal(sequence, node);
expect(sequence).toBe(node);
const block = t.blockStatement([t.expressionStatement(node)]);
sequence = t.toSequenceExpression([block], scope);
assert.equal(sequence, node);
expect(sequence).toBe(node);
});
it("gathers expression", function() {
const node = t.identifier("a");
const sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.equal(sequence.expressions[1], node);
expect(sequence.expressions[1]).toBe(node);
});
it("gathers expression statement", function() {
const node = t.expressionStatement(t.identifier("a"));
const sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.equal(sequence.expressions[1], node.expression);
expect(sequence.expressions[1]).toBe(node.expression);
});
it("gathers var declarations", function() {
const node = parseCode("var a, b = 1;");
const sequence = t.toSequenceExpression([undefinedNode, node], scope);
t.assertIdentifier(scope[0].id, { name: "a" });
t.assertIdentifier(scope[1].id, { name: "b" });
assert.equal(generateCode(sequence.expressions[1]), "b = 1");
assert.equal(generateCode(sequence.expressions[2]), "undefined");
expect(generateCode(sequence.expressions[1])).toBe("b = 1");
expect(generateCode(sequence.expressions[2])).toBe("undefined");
});
it("skips undefined if expression after var declaration", function() {
const node = parseCode("{ var a, b = 1; true }");
const sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.equal(generateCode(sequence.expressions[1]), "b = 1, true");
expect(generateCode(sequence.expressions[1])).toBe("b = 1, true");
});
it("bails on let and const declarations", function() {
let node = parseCode("let a, b = 1;");
let sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.isUndefined(sequence);
expect(sequence).toBeUndefined();
node = parseCode("const b = 1;");
sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.isUndefined(sequence);
expect(sequence).toBeUndefined();
});
it("gathers if statements", function() {
let node = parseCode("if (true) { true }");
let sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.equal(
generateCode(sequence.expressions[1]),
expect(generateCode(sequence.expressions[1])).toBe(
"true ? true : undefined",
);
node = parseCode("if (true) { true } else { b }");
sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.equal(generateCode(sequence.expressions[1]), "true ? true : b");
expect(generateCode(sequence.expressions[1])).toBe("true ? true : b");
});
it("bails in if statements if recurse bails", function() {
let node = parseCode("if (true) { return }");
let sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.isUndefined(sequence);
expect(sequence).toBeUndefined();
node = parseCode("if (true) { true } else { return }");
sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.isUndefined(sequence);
expect(sequence).toBeUndefined();
});
it("gathers block statements", function() {
let node = parseCode("{ a }");
let sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.equal(generateCode(sequence.expressions[1]), "a");
expect(generateCode(sequence.expressions[1])).toBe("a");
node = parseCode("{ a; b; }");
sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.equal(generateCode(sequence.expressions[1]), "a, b");
expect(generateCode(sequence.expressions[1])).toBe("a, b");
});
it("bails in block statements if recurse bails", function() {
const node = parseCode("{ return }");
const sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.isUndefined(sequence);
expect(sequence).toBeUndefined();
});
it("gathers empty statements", function() {
const node = parseCode(";");
const sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.equal(generateCode(sequence.expressions[1]), "undefined");
expect(generateCode(sequence.expressions[1])).toBe("undefined");
});
it("skips empty statement if expression afterwards", function() {
const node = parseCode("{ ; true }");
const sequence = t.toSequenceExpression([undefinedNode, node], scope);
assert.equal(generateCode(sequence.expressions[1]), "true");
expect(generateCode(sequence.expressions[1])).toBe("true");
});
});
});

View File

@ -1,84 +1,83 @@
import * as t from "../lib";
import assert from "assert";
import { parse } from "babylon";
suite("validators", function() {
suite("isNodesEquivalent", function() {
describe("validators", function() {
describe("isNodesEquivalent", function() {
it("should handle simple cases", function() {
const mem = t.memberExpression(t.identifier("a"), t.identifier("b"));
assert(t.isNodesEquivalent(mem, mem) === true);
expect(t.isNodesEquivalent(mem, mem)).toBe(true);
const mem2 = t.memberExpression(t.identifier("a"), t.identifier("c"));
assert(t.isNodesEquivalent(mem, mem2) === false);
expect(t.isNodesEquivalent(mem, mem2)).toBe(false);
});
it("should handle full programs", function() {
assert(t.isNodesEquivalent(parse("1 + 1"), parse("1+1")) === true);
assert(t.isNodesEquivalent(parse("1 + 1"), parse("1+2")) === false);
expect(t.isNodesEquivalent(parse("1 + 1"), parse("1+1"))).toBe(true);
expect(t.isNodesEquivalent(parse("1 + 1"), parse("1+2"))).toBe(false);
});
it("should handle complex programs", function() {
const program = "'use strict'; function lol() { wow();return 1; }";
assert(t.isNodesEquivalent(parse(program), parse(program)) === true);
expect(t.isNodesEquivalent(parse(program), parse(program))).toBe(true);
const program2 = "'use strict'; function lol() { wow();return -1; }";
assert(t.isNodesEquivalent(parse(program), parse(program2)) === false);
expect(t.isNodesEquivalent(parse(program), parse(program2))).toBe(false);
});
it("rejects 'await' as an identifier", function() {
assert(t.isValidIdentifier("await") === false);
expect(t.isValidIdentifier("await")).toBe(false);
});
});
suite("isCompatTag", function() {
describe("isCompatTag", function() {
it("should handle lowercase tag names", function() {
assert(t.react.isCompatTag("div"));
assert(t.react.isCompatTag("a")); // one letter
assert(t.react.isCompatTag("h3")); // letters and numbers
expect(t.react.isCompatTag("div")).toBe(true);
expect(t.react.isCompatTag("a")).toBe(true); // one letter
expect(t.react.isCompatTag("h3")).toBe(true); // letters and numbers
});
it("should handle custom element tag names", function() {
assert(t.react.isCompatTag("plastic-button")); // ascii letters
assert(t.react.isCompatTag("math-α")); // non-latin chars
assert(t.react.isCompatTag("img-viewer2")); // numbers
assert(t.react.isCompatTag("emotion-😍")); // emoji
expect(t.react.isCompatTag("plastic-button")).toBe(true); // ascii letters
expect(t.react.isCompatTag("math-α")).toBe(true); // non-latin chars
expect(t.react.isCompatTag("img-viewer2")).toBe(true); // numbers
expect(t.react.isCompatTag("emotion-😍")).toBe(true); // emoji
});
it("accepts trailing dash '-' in custom element tag names", function() {
assert(t.react.isCompatTag("div-"));
assert(t.react.isCompatTag("a-"));
assert(t.react.isCompatTag("h3-"));
expect(t.react.isCompatTag("div-")).toBe(true);
expect(t.react.isCompatTag("a-")).toBe(true);
expect(t.react.isCompatTag("h3-")).toBe(true);
});
it("rejects empty or null tag names", function() {
assert(t.react.isCompatTag(null) === false);
assert(t.react.isCompatTag() === false);
assert(t.react.isCompatTag(undefined) === false);
assert(t.react.isCompatTag("") === false);
expect(t.react.isCompatTag(null)).toBe(false);
expect(t.react.isCompatTag()).toBe(false);
expect(t.react.isCompatTag(undefined)).toBe(false);
expect(t.react.isCompatTag("")).toBe(false);
});
it("rejects tag names starting with an uppercase letter", function() {
assert(t.react.isCompatTag("Div") === false);
assert(t.react.isCompatTag("A") === false);
assert(t.react.isCompatTag("H3") === false);
expect(t.react.isCompatTag("Div")).toBe(false);
expect(t.react.isCompatTag("A")).toBe(false);
expect(t.react.isCompatTag("H3")).toBe(false);
});
it("rejects all uppercase tag names", function() {
assert(t.react.isCompatTag("DIV") === false);
assert(t.react.isCompatTag("A") === false);
assert(t.react.isCompatTag("H3") === false);
expect(t.react.isCompatTag("DIV")).toBe(false);
expect(t.react.isCompatTag("A")).toBe(false);
expect(t.react.isCompatTag("H3")).toBe(false);
});
it("rejects leading dash '-'", function() {
assert(t.react.isCompatTag("-div") === false);
assert(t.react.isCompatTag("-a") === false);
assert(t.react.isCompatTag("-h3") === false);
expect(t.react.isCompatTag("-div")).toBe(false);
expect(t.react.isCompatTag("-a")).toBe(false);
expect(t.react.isCompatTag("-h3")).toBe(false);
});
});
suite("patterns", function() {
describe("patterns", function() {
it("allows nested pattern structures", function() {
const pattern = t.objectPattern([
t.objectProperty(
@ -93,7 +92,7 @@ suite("validators", function() {
),
]);
assert(t.isNodesEquivalent(pattern, pattern) === true);
expect(t.isNodesEquivalent(pattern, pattern)).toBe(true);
});
});
});

View File

@ -1,24 +0,0 @@
#!/bin/bash
set -e
TEST_DIRS=""
sources=("codemods" "packages")
for source in "${sources[@]}"; do
for f in $source/*; do
if [ -n "$TEST_ONLY" ] && [[ `basename $f` != *"$TEST_ONLY"* ]]; then
continue
fi
# Exclude babel-standalone from coverage runs
if [ "$TEST_TYPE" = "cov" ] && [[ `basename $f` = 'babel-standalone' || `basename $f` = 'babel-preset-env-standalone' ]]; then
continue
fi
if [ -d "$f/test" ]; then
TEST_DIRS="$f/test $TEST_DIRS"
fi
done
done
echo $TEST_DIRS

View File

@ -1,6 +1,10 @@
#!/bin/bash
set -e
testDirs=`TEST_TYPE=cov scripts/_get-test-directories.sh`
node_modules/.bin/nyc node_modules/mocha/bin/_mocha --opts test/mocha.opts $testDirs
node_modules/.bin/nyc report --reporter=json
jestArgs="--coverage"
if [ -n "$CI" ]; then
jestArgs="${jestArgs} --runInBand --ci"
fi
node_modules/.bin/jest $jestArgs

View File

@ -6,9 +6,15 @@ if [ -z "$TEST_GREP" ]; then
fi
node="node"
jestArgs=""
if [ "$TEST_DEBUG" ]; then
node="node --inspect-brk"
jestArgs="${jestArgs} --runInBand"
fi
$node node_modules/mocha/bin/_mocha `scripts/_get-test-directories.sh` --opts test/mocha.opts --grep "$TEST_GREP"
if [ -n "$CI" ]; then
jestArgs="${jestArgs} --runInBand --ci"
fi
$node node_modules/.bin/jest $jestArgs "$TEST_GREP"

View File

@ -1 +0,0 @@
--reporter dot --ui tdd --timeout 10000 --compilers js:@babel/register

1
test/testSetupFile.js Normal file
View File

@ -0,0 +1 @@
jest.setTimeout(10000);

2122
yarn.lock

File diff suppressed because it is too large Load Diff