Skip to content

Commit

Permalink
Use newer ES syntax where possible
Browse files Browse the repository at this point in the history
As detected via XO. Also apply other XO fixes.
  • Loading branch information
sindresorhus authored and novemberborn committed Dec 17, 2018
1 parent 783944f commit 7b6e578
Show file tree
Hide file tree
Showing 76 changed files with 305 additions and 169 deletions.
11 changes: 7 additions & 4 deletions api.js
Expand Up @@ -45,9 +45,8 @@ class Api extends Emittery {
this._precompiler = null;
}

run(files, runtimeOptions) {
run(files, runtimeOptions = {}) {
const apiOptions = this.options;
runtimeOptions = runtimeOptions || {};

// Each run will have its own status. It can only be created when test files
// have been found.
Expand Down Expand Up @@ -161,9 +160,10 @@ class Api extends Emittery {
if (cachePath) {
acc[realpath] = cachePath;
}
} catch (err) {
throw Object.assign(err, {file});
} catch (error) {
throw Object.assign(error, {file});
}

return acc;
}, {})
};
Expand All @@ -175,6 +175,7 @@ class Api extends Emittery {
if (apiOptions.concurrency > 0) {
concurrency = apiOptions.concurrency;
}

if (apiOptions.serial) {
concurrency = 1;
}
Expand All @@ -198,6 +199,7 @@ class Api extends Emittery {
} else {
options.precompiled = {};
}

if (runtimeOptions.updateSnapshots) {
// Don't use in Object.assign() since it'll override options.updateSnapshots even when false.
options.updateSnapshots = true;
Expand Down Expand Up @@ -245,6 +247,7 @@ class Api extends Emittery {
filename => {
throw new Error(`Cannot apply full precompilation, possible bad usage: ${filename}`);
};

let precompileEnhancementsOnly = () => null;
if (compileEnhancements) {
precompileEnhancementsOnly = this.options.extensions.enhancementsOnly.length > 0 ?
Expand Down
2 changes: 1 addition & 1 deletion bench/run.js
Expand Up @@ -101,7 +101,7 @@ for (let i = 0; i < 11; i++) {
const results = {};

Promise.each(combined, definition => {
const args = definition.args;
const {args} = definition;

return runTests(args).then(result => {
const key = result.args.join(' ');
Expand Down
10 changes: 6 additions & 4 deletions lib/assert.js
Expand Up @@ -221,10 +221,7 @@ function assertExpectations({assertion, actual, expectations, message, prefix, s
}

function wrapAssertions(callbacks) {
const pass = callbacks.pass;
const pending = callbacks.pending;
const fail = callbacks.fail;

const {pass, pending, fail} = callbacks;
const noop = () => {};

const assertions = {
Expand Down Expand Up @@ -336,6 +333,7 @@ function wrapAssertions(callbacks) {
try {
retval.catch(noop);
} catch (_) {}

fail(this, new AssertionError({
assertion: 'throws',
message,
Expand Down Expand Up @@ -539,6 +537,7 @@ function wrapAssertions(callbacks) {
} else if (optionsOrMessage) {
options.id = optionsOrMessage.id;
}

options.expected = expected;
options.message = message;

Expand Down Expand Up @@ -633,6 +632,7 @@ function wrapAssertions(callbacks) {
values: [formatWithLabel('Called with:', string)]
});
}

if (!(regex instanceof RegExp)) {
throw new AssertionError({
assertion: 'regex',
Expand Down Expand Up @@ -663,6 +663,7 @@ function wrapAssertions(callbacks) {
values: [formatWithLabel('Called with:', string)]
});
}

if (!(regex instanceof RegExp)) {
throw new AssertionError({
assertion: 'notRegex',
Expand All @@ -687,4 +688,5 @@ function wrapAssertions(callbacks) {

return Object.assign(assertions, enhancedAssertions);
}

exports.wrapAssertions = wrapAssertions;
7 changes: 3 additions & 4 deletions lib/ava-files.js
Expand Up @@ -101,9 +101,7 @@ const getDefaultIgnorePatterns = () => defaultIgnore.map(dir => `${dir}/**/*`);
const matchable = process.platform === 'win32' ? slash : (path => path);

class AvaFiles {
constructor(options) {
options = options || {};

constructor(options = {}) {
let files = (options.files || []).map(file => {
// `./` should be removed from the beginning of patterns because
// otherwise they won't match change events from Chokidar
Expand All @@ -121,6 +119,7 @@ class AvaFiles {
if (files.length === 0) {
files = defaultIncludePatterns(this.extensionPattern);
}

this.files = files;
this.sources = options.sources || [];
this.cwd = options.cwd || process.cwd();
Expand Down Expand Up @@ -202,7 +201,7 @@ class AvaFiles {
}

isTest(filePath) {
const excludePatterns = this.excludePatterns;
const {excludePatterns} = this;
const initialPatterns = this.files.concat(excludePatterns);

// Like in `api.js`, tests must be `.js` files and not start with `_`
Expand Down
5 changes: 5 additions & 0 deletions lib/babel-pipeline.js
Expand Up @@ -114,6 +114,7 @@ function hashPartialTestConfig({babelrc, config, options: {plugins, presets}}, p
inputs.push(stripBomBuf(fs.readFileSync(babelrc)));
}
}

if (config) {
inputs.push(config, stripBomBuf(fs.readFileSync(config)));
}
Expand Down Expand Up @@ -196,16 +197,20 @@ function build(projectDir, cacheDir, userOptions, compileEnhancements) {
if (!testOptions.plugins.some(containsAsyncGenerators)) { // TODO: Remove once Babel can parse this syntax unaided.
testOptions.plugins.unshift(createConfigItem('@babel/plugin-syntax-async-generators', 'plugin'));
}

if (!testOptions.plugins.some(containsObjectRestSpread)) { // TODO: Remove once Babel can parse this syntax unaided.
testOptions.plugins.unshift(createConfigItem('@babel/plugin-syntax-object-rest-spread', 'plugin'));
}

if (!testOptions.plugins.some(containsOptionalCatchBinding)) { // TODO: Remove once Babel can parse this syntax unaided.
testOptions.plugins.unshift(createConfigItem('@babel/plugin-syntax-optional-catch-binding', 'plugin'));
}

if (ensureStage4 && !testOptions.presets.some(containsStage4)) {
// Apply last.
testOptions.presets.unshift(createConfigItem('../stage-4', 'preset'));
}

if (compileEnhancements && !testOptions.presets.some(containsTransformTestFiles)) {
// Apply first.
testOptions.presets.push(createConfigItem('@ava/babel-preset-transform-test-files', 'preset', {powerAssert: true}));
Expand Down
3 changes: 3 additions & 0 deletions lib/chalk.js
Expand Up @@ -6,12 +6,15 @@ exports.get = () => {
if (!ctx) {
throw new Error('Chalk has not yet been configured');
}

return ctx;
};

exports.set = options => {
if (ctx) {
throw new Error('Chalk has already been configured');
}

ctx = new Chalk(options);
return ctx;
};
7 changes: 2 additions & 5 deletions lib/code-excerpt.js
Expand Up @@ -8,15 +8,12 @@ const chalk = require('./chalk').get();
const formatLineNumber = (lineNumber, maxLineNumber) =>
' '.repeat(Math.max(0, String(maxLineNumber).length - String(lineNumber).length)) + lineNumber;

module.exports = (source, options) => {
module.exports = (source, options = {}) => {
if (!source.isWithinProject || source.isDependency) {
return null;
}

const file = source.file;
const line = source.line;

options = options || {};
const {file, line} = source;
const maxWidth = options.maxWidth || 80;

let contents;
Expand Down
1 change: 1 addition & 0 deletions lib/context-ref.js
Expand Up @@ -31,6 +31,7 @@ class LateBinding extends ContextRef {
if (!this.bound) {
this.set(clone(this.ref.get()));
}

return super.get();
}

Expand Down
12 changes: 8 additions & 4 deletions lib/create-chain.js
Expand Up @@ -2,9 +2,10 @@
const chainRegistry = new WeakMap();

function startChain(name, call, defaults) {
const fn = function () {
call(Object.assign({}, defaults), Array.from(arguments));
const fn = (...args) => {
call(Object.assign({}, defaults), args);
};

Object.defineProperty(fn, 'name', {value: name});
chainRegistry.set(fn, {call, defaults, fullName: name});
return fn;
Expand All @@ -15,9 +16,10 @@ function extendChain(prev, name, flag) {
flag = name;
}

const fn = function () {
callWithFlag(prev, flag, Array.from(arguments));
const fn = (...args) => {
callWithFlag(prev, flag, args);
};

const fullName = `${chainRegistry.get(prev).fullName}.${name}`;
Object.defineProperty(fn, 'name', {value: fullName});
prev[name] = fn;
Expand Down Expand Up @@ -55,6 +57,7 @@ function createHookChain(hook, isAfterHook) {
extendChain(hook.always, 'skip', 'skipped');
extendChain(hook.always.cb, 'skip', 'skipped');
}

return hook;
}

Expand Down Expand Up @@ -107,4 +110,5 @@ function createChain(fn, defaults) {

return root;
}

module.exports = createChain;
4 changes: 3 additions & 1 deletion lib/enhance-assert.js
Expand Up @@ -37,10 +37,11 @@ const enhanceAssert = (pass, fail, assertions) => {
return empower(assertions, {
destructive: true,
onError(event) {
const error = event.error;
const {error} = event;
if (event.powerAssertContext) { // Context may be missing in internal tests.
error.statements = formatter(event.powerAssertContext);
}

fail(this, error);
},
onSuccess() {
Expand All @@ -50,4 +51,5 @@ const enhanceAssert = (pass, fail, assertions) => {
bindReceiver: false
});
};

module.exports = enhanceAssert;
1 change: 1 addition & 0 deletions lib/extensions.js
Expand Up @@ -19,6 +19,7 @@ module.exports = (enhancementsOnly, babelConfig) => {
seen.add('js');
full.push('js');
}

if (!babelConfig && enhancementsOnly.length === 0) {
seen.add('js');
enhancementsOnly.push('js');
Expand Down
4 changes: 4 additions & 0 deletions lib/load-config.js
Expand Up @@ -39,6 +39,7 @@ function loadConfig(defaults = {}) {
if (fileConf && typeof fileConf.then === 'function') {
throw new TypeError('ava.config.js must not export a promise');
}

if (!isPlainObject(fileConf) && typeof fileConf !== 'function') {
throw new TypeError('ava.config.js must export a plain object or factory function');
}
Expand All @@ -48,15 +49,18 @@ function loadConfig(defaults = {}) {
if (fileConf && typeof fileConf.then === 'function') {
throw new TypeError('Factory method exported by ava.config.js must not return a promise');
}

if (!isPlainObject(fileConf)) {
throw new TypeError('Factory method exported by ava.config.js must return a plain object');
}
}

if ('ava' in fileConf) {
throw new Error('Encountered \'ava\' property in ava.config.js; avoid wrapping the configuration');
}
}

return Object.assign({}, defaults, fileConf, packageConf, {projectDir});
}

module.exports = loadConfig;
1 change: 1 addition & 0 deletions lib/reporters/format-serialized-error.js
Expand Up @@ -23,4 +23,5 @@ function formatSerializedError(error) {
formatted = trimOffNewlines(formatted);
return {formatted, printMessage};
}

module.exports = formatSerializedError;
8 changes: 3 additions & 5 deletions lib/reporters/improper-usage-messages.js
Expand Up @@ -7,7 +7,7 @@ exports.forError = error => {
return null;
}

const assertion = error.assertion;
const {assertion} = error;
if (assertion === 'throws' || assertion === 'notThrows') {
return `Try wrapping the first argument to \`t.${assertion}()\` in a function:
Expand All @@ -19,8 +19,7 @@ Visit the following URL for more details:
}

if (assertion === 'snapshot') {
const name = error.improperUsage.name;
const snapPath = error.improperUsage.snapPath;
const {name, snapPath} = error.improperUsage;

if (name === 'ChecksumError') {
return `The snapshot file is corrupted.
Expand All @@ -39,8 +38,7 @@ Please run AVA again with the ${chalk.cyan('--update-snapshots')} flag to upgrad
}

if (name === 'VersionMismatchError') {
const snapVersion = error.improperUsage.snapVersion;
const expectedVersion = error.improperUsage.expectedVersion;
const {snapVersion, expectedVersion} = error.improperUsage;
const upgradeMessage = snapVersion < expectedVersion ?
`Please run AVA again with the ${chalk.cyan('--update-snapshots')} flag to upgrade.` :
'You should upgrade AVA.';
Expand Down

0 comments on commit 7b6e578

Please sign in to comment.