Skip to content

Commit

Permalink
Modernize some syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
novemberborn committed Jul 2, 2023
1 parent 6cc417b commit e5f19d9
Show file tree
Hide file tree
Showing 23 changed files with 62 additions and 62 deletions.
2 changes: 1 addition & 1 deletion examples/macros/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ function macro(t, a, b, expected) {
t.is(sum(a, b), expected);
}

macro.title = (providedTitle, a, b, expected) => `${providedTitle || ''} ${a}+${b} = ${expected}`.trim();
macro.title = (providedTitle, a, b, expected) => `${providedTitle ?? ''} ${a}+${b} = ${expected}`.trim();

test(macro, 2, 2, 4);
test(macro, 3, 3, 6);
Expand Down
8 changes: 4 additions & 4 deletions lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ export default class Api extends Emittery {

const selectionInsights = {
filter,
ignoredFilterPatternFiles: selectedFiles.ignoredFilterPatternFiles || [],
ignoredFilterPatternFiles: selectedFiles.ignoredFilterPatternFiles ?? [],
testFileCount: testFiles.length,
selectionCount: selectedFiles.length,
};
Expand All @@ -176,7 +176,7 @@ export default class Api extends Emittery {

// The files must be in the same order across all runs, so sort them.
const defaultComparator = (a, b) => a.localeCompare(b, [], {numeric: true});
selectedFiles = selectedFiles.sort(this.options.sortTestFiles || defaultComparator);
selectedFiles = selectedFiles.sort(this.options.sortTestFiles ?? defaultComparator);
selectedFiles = chunkd(selectedFiles, currentIndex, totalRuns);

const currentFileCount = selectedFiles.length;
Expand All @@ -202,7 +202,7 @@ export default class Api extends Emittery {
filePathPrefix: getFilePathPrefix(selectedFiles),
files: selectedFiles,
matching: apiOptions.match.length > 0,
previousFailures: runtimeOptions.previousFailures || 0,
previousFailures: runtimeOptions.previousFailures ?? 0,
runOnlyExclusive: runtimeOptions.runOnlyExclusive === true,
firstRun: runtimeOptions.firstRun ?? true,
status: runStatus,
Expand Down Expand Up @@ -305,7 +305,7 @@ export default class Api extends Emittery {
const files = scheduler.storeFailedTestFiles(runStatus, this.options.cacheEnabled === false ? null : this._createCacheDir());
runStatus.emitStateChange({type: 'touched-files', files});
} catch (error) {
if (error && error.name === 'AggregateError') {
if (error?.name === 'AggregateError') {
for (const error_ of error.errors) {
runStatus.emitStateChange({type: 'internal-error', err: serializeError('Internal error', false, error_)});
}
Expand Down
32 changes: 16 additions & 16 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,22 @@ const notImplemented = () => {

export class AssertionError extends Error {
constructor(options) {
super(options.message || '');
super(options.message ?? '');
this.name = 'AssertionError';

this.assertion = options.assertion;
this.fixedSource = options.fixedSource;
this.improperUsage = options.improperUsage || false;
this.improperUsage = options.improperUsage ?? false;
this.actualStack = options.actualStack;
this.operator = options.operator;
this.values = options.values || [];
this.values = options.values ?? [];

// Raw expected and actual objects are stored for custom reporters
// (such as wallaby.js), that manage worker processes directly and
// use the values for custom diff views
this.raw = options.raw;

this.savedError = options.savedError || getErrorWithLongStackTrace();
this.savedError = options.savedError ?? getErrorWithLongStackTrace();
}
}

Expand Down Expand Up @@ -303,7 +303,7 @@ export class Assertions {

fail(new AssertionError({
assertion: 'fail',
message: message || 'Test failed via `t.fail()`',
message: message ?? 'Test failed via `t.fail()`',
}));

return false;
Expand All @@ -320,8 +320,8 @@ export class Assertions {
}

const result = concordance.compare(actual, expected, concordanceOptions);
const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);
const expectedDescriptor = result.expected || concordance.describe(expected, concordanceOptions);
const actualDescriptor = result.actual ?? concordance.describe(actual, concordanceOptions);
const expectedDescriptor = result.expected ?? concordance.describe(expected, concordanceOptions);

if (result.pass) {
fail(new AssertionError({
Expand Down Expand Up @@ -372,8 +372,8 @@ export class Assertions {
return true;
}

const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);
const expectedDescriptor = result.expected || concordance.describe(expected, concordanceOptions);
const actualDescriptor = result.actual ?? concordance.describe(actual, concordanceOptions);
const expectedDescriptor = result.expected ?? concordance.describe(expected, concordanceOptions);
fail(new AssertionError({
assertion: 'deepEqual',
message,
Expand All @@ -390,7 +390,7 @@ export class Assertions {

const result = concordance.compare(actual, expected, concordanceOptions);
if (result.pass) {
const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);
const actualDescriptor = result.actual ?? concordance.describe(actual, concordanceOptions);
fail(new AssertionError({
assertion: 'notDeepEqual',
message,
Expand Down Expand Up @@ -442,8 +442,8 @@ export class Assertions {
return true;
}

const actualDescriptor = result.actual || concordance.describe(comparable, concordanceOptions);
const expectedDescriptor = result.expected || concordance.describe(selector, concordanceOptions);
const actualDescriptor = result.actual ?? concordance.describe(comparable, concordanceOptions);
const expectedDescriptor = result.expected ?? concordance.describe(selector, concordanceOptions);
fail(new AssertionError({
assertion: 'like',
message,
Expand Down Expand Up @@ -715,7 +715,7 @@ export class Assertions {
return false;
}

if (message && message.id !== undefined) {
if (message?.id !== undefined) {
fail(new AssertionError({
assertion: 'snapshot',
message: 'AVA 4 no longer supports snapshot IDs',
Expand Down Expand Up @@ -755,7 +755,7 @@ export class Assertions {

fail(new AssertionError({
assertion: 'snapshot',
message: message || 'Could not compare snapshot',
message: message ?? 'Could not compare snapshot',
improperUsage,
}));
return false;
Expand All @@ -769,14 +769,14 @@ export class Assertions {
if (result.actual) {
fail(new AssertionError({
assertion: 'snapshot',
message: message || 'Did not match snapshot',
message: message ?? 'Did not match snapshot',
values: [formatDescriptorDiff(result.actual, result.expected, {invert: true})],
}));
} else {
// This can only occur in CI environments.
fail(new AssertionError({
assertion: 'snapshot',
message: message || 'No snapshot available — new snapshots are not created in CI environments',
message: message ?? 'No snapshot available — new snapshots are not created in CI environments',
}));
}

Expand Down
12 changes: 6 additions & 6 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export default async function loadCli() { // eslint-disable-line complexity
type: 'string',
}), argv => {
if (activeInspector) {
debug.files = argv.pattern || [];
debug.files = argv.pattern ?? [];
}
})
.command(
Expand Down Expand Up @@ -283,7 +283,7 @@ export default async function loadCli() { // eslint-disable-line complexity

process.exit(0); // eslint-disable-line unicorn/no-process-exit
} catch (error) {
exit(`Error removing AVA cache files in ${cacheDir}\n\n${chalk.gray((error && error.stack) || error)}`);
exit(`Error removing AVA cache files in ${cacheDir}\n\n${chalk.gray(error?.stack ?? error)}`);
}
}

Expand Down Expand Up @@ -344,7 +344,7 @@ export default async function loadCli() { // eslint-disable-line complexity
}
}

const {type: defaultModuleType = 'commonjs'} = projectPackageObject || {};
const {type: defaultModuleType = 'commonjs'} = projectPackageObject ?? {};

const providers = [];
if (Object.hasOwn(conf, 'typescript')) {
Expand Down Expand Up @@ -404,7 +404,7 @@ export default async function loadCli() { // eslint-disable-line complexity

const match = combined.match === '' ? [] : arrify(combined.match);

const input = debug ? debug.files : (argv.pattern || []);
const input = debug ? debug.files : (argv.pattern ?? []);
const filter = input
.map(pattern => splitPatternAndLineNumbers(pattern))
.map(({pattern, ...rest}) => ({
Expand All @@ -415,7 +415,7 @@ export default async function loadCli() { // eslint-disable-line complexity
const api = new Api({
cacheEnabled: combined.cache !== false,
chalkOptions,
concurrency: combined.concurrency || 0,
concurrency: combined.concurrency ?? 0,
workerThreads: combined.workerThreads !== false,
debug,
enableAva5DependencyTracking: argv.watch && conf.watchMode?.implementation === 'ava5+chokidar',
Expand All @@ -436,7 +436,7 @@ export default async function loadCli() { // eslint-disable-line complexity
require: arrify(combined.require),
serial: combined.serial,
snapshotDir: combined.snapshotDir ? path.resolve(projectDir, combined.snapshotDir) : null,
timeout: combined.timeout || '10s',
timeout: combined.timeout ?? '10s',
updateSnapshots: combined.updateSnapshots,
workerArgv: argv['--'],
});
Expand Down
4 changes: 2 additions & 2 deletions lib/code-excerpt.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import {chalk} from './chalk.js';
const formatLineNumber = (lineNumber, maxLineNumber) =>
' '.repeat(Math.max(0, String(maxLineNumber).length - String(lineNumber).length)) + lineNumber;

export default function exceptCode(source, options = {}) {
export default function excerptCode(source, options = {}) {
if (!source.isWithinProject || source.isDependency) {
return null;
}

const {file, line} = source;
const maxWidth = options.maxWidth || 80;
const maxWidth = (options.maxWidth ?? 0) || 80;

let contents;
try {
Expand Down
2 changes: 1 addition & 1 deletion lib/eslint-plugin-helper-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const buildGlobs = ({conf, providers, projectDir, overrideExtensions, overrideFi
cwd: projectDir,
...normalizeGlobs({
extensions,
files: overrideFiles || conf.files,
files: overrideFiles ?? conf.files,
providers,
}),
};
Expand Down
2 changes: 1 addition & 1 deletion lib/fork.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const createWorker = (options, execArgv) => {

// Ensure we've seen this event before we terminate the worker thread, as a
// workaround for https://github.com/nodejs/node/issues/38418.
const starting = pEvent(worker, 'message', ({ava}) => ava && ava.type === 'starting');
const starting = pEvent(worker, 'message', ({ava}) => ava?.type === 'starting');

close = async () => {
try {
Expand Down
2 changes: 1 addition & 1 deletion lib/load-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ function resolveConfigFile(configFile) {
return configFile;
}

const gitScmFile = process.env.AVA_FAKE_SCM_ROOT || '.git';
const gitScmFile = process.env.AVA_FAKE_SCM_ROOT ?? '.git';

async function findRepoRoot(fromDir) {
const {root} = path.parse(fromDir);
Expand Down
4 changes: 2 additions & 2 deletions lib/parse-test-args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const buildTitle = (raw, implementation, args) => {
let value = implementation && implementation.title ? implementation.title(raw, ...args) : raw;
let value = implementation?.title?.(raw, ...args) ?? raw;
const isValid = typeof value === 'string';
if (isValid) {
value = value.trim().replace(/\s+/g, ' ');
Expand All @@ -20,7 +20,7 @@ export default function parseTestArgs(args) {

return {
args,
implementation: implementation && implementation.exec ? implementation.exec : implementation,
implementation: implementation?.exec ?? implementation,
title: buildTitle(rawTitle, implementation, args),
};
}
10 changes: 5 additions & 5 deletions lib/reporters/default.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class LineWriter extends stream.Writable {
super();

this.dest = dest;
this.columns = dest.columns || 80;
this.columns = dest.columns ?? 80;
this.lastLineIsEmpty = false;
}

Expand Down Expand Up @@ -91,7 +91,7 @@ export default class Reporter {
this.consumeStateChange = decorateWriter(this.consumeStateChange);
this.endRun = decorateWriter(this.endRun);

this.durationThreshold = durationThreshold || 100;
this.durationThreshold = durationThreshold ?? 100;
this.lineWriter = new LineWriter(this.reportStream);

this.reset();
Expand Down Expand Up @@ -390,7 +390,7 @@ export default class Reporter {
return this.lineWriter.writeLine(string);
}

string = string || '';
string ??= '';
if (string !== '') {
string += os.EOL;
}
Expand Down Expand Up @@ -428,7 +428,7 @@ export default class Reporter {
}

writeErr(event) {
if (event.err.name === 'TSError' && event.err.object && event.err.object.diagnosticText) {
if (event.err.name === 'TSError' && event.err.object?.diagnosticText) {
this.lineWriter.writeLine(colors.errorStack(event.err.object.diagnosticText));
this.lineWriter.writeLine();
return;
Expand Down Expand Up @@ -495,7 +495,7 @@ export default class Reporter {
}

writeLogs(event, surroundLines) {
if (event.logs && event.logs.length > 0) {
if (event.logs?.length > 0) {
if (surroundLines) {
this.lineWriter.writeLine();
}
Expand Down
2 changes: 1 addition & 1 deletion lib/reporters/tap.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export default class TapReporter {

writeCrash(evt, title) {
this.crashCount++;
this.reportStream.write(supertap.test(title || evt.err.summary || evt.type, {
this.reportStream.write(supertap.test(title ?? evt.err.summary ?? evt.type, {
comment: evt.logs,
error: evt.err ? dumpError(evt.err) : null,
index: ++this.i,
Expand Down
8 changes: 4 additions & 4 deletions lib/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ export default class Runner extends Emittery {
constructor(options = {}) {
super();

this.experiments = options.experiments || {};
this.experiments = options.experiments ?? {};
this.failFast = options.failFast === true;
this.failWithoutAssertions = options.failWithoutAssertions !== false;
this.file = options.file;
this.checkSelectedByLineNumbers = options.checkSelectedByLineNumbers;
this.match = options.match || [];
this.match = options.match ?? [];
this.projectDir = options.projectDir;
this.recordNewSnapshots = options.recordNewSnapshots === true;
this.runOnlyExclusive = options.runOnlyExclusive === true;
Expand Down Expand Up @@ -151,7 +151,7 @@ export default class Runner extends Emittery {
}

const task = {
title: title.value || fallbackTitle,
title: title.value ?? fallbackTitle,
implementation,
args,
metadata: {...metadata},
Expand Down Expand Up @@ -301,7 +301,7 @@ export default class Runner extends Emittery {
skipSnapshot: this.boundSkipSnapshot,
updateSnapshots: this.updateSnapshots,
metadata: task.metadata,
title: `${task.title}${titleSuffix || ''}`,
title: `${task.title}${titleSuffix ?? ''}`,
isHook: true,
testPassed,
notifyTimeoutUpdate: this.notifyTimeoutUpdate,
Expand Down
6 changes: 3 additions & 3 deletions lib/snapshot-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,8 @@ class Manager {

const block = this.newBlocksByTitle.get(options.belongsTo);

const snapshot = block && block.snapshots[options.index];
const data = snapshot && snapshot.data;
const snapshot = block?.snapshots[options.index];
const data = snapshot?.data;

if (!data) {
if (!this.recordNewSnapshots) {
Expand Down Expand Up @@ -332,7 +332,7 @@ class Manager {

skipSnapshot({belongsTo, index, deferRecording}) {
const oldBlock = this.oldBlocksByTitle.get(belongsTo);
let snapshot = oldBlock && oldBlock.snapshots[index];
let snapshot = oldBlock?.snapshots[index];

if (!snapshot) {
snapshot = {};
Expand Down
4 changes: 2 additions & 2 deletions lib/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ class ExecutionContext extends Assertions {
export default class Test {
constructor(options) {
this.contextRef = options.contextRef;
this.experiments = options.experiments || {};
this.experiments = options.experiments ?? {};
this.failWithoutAssertions = options.failWithoutAssertions;
this.fn = options.fn;
this.isHook = options.isHook === true;
Expand Down Expand Up @@ -420,7 +420,7 @@ export default class Test {
this.clearTimeout();
this.timeoutMs = ms;
this.timeoutTimer = nowAndTimers.setCappedTimeout(() => {
this.saveFirstError(new Error(message || 'Test timeout exceeded'));
this.saveFirstError(new Error(message ?? 'Test timeout exceeded'));

if (this.finishDueToTimeout) {
this.finishDueToTimeout();
Expand Down
Loading

0 comments on commit e5f19d9

Please sign in to comment.