Skip to content

Modernize some code #1876

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 34 additions & 35 deletions bench/compare.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,14 @@ const results = {};
const fileNames = files.map(file => file['.file']);
const stats = ['mean', 'stdDev', 'median', 'min', 'max'];

files.forEach(file => {
for (const file of files) {
Object.keys(file)
.filter(key => !/^\./.test(key))
.filter(key => !key.startsWith('.'))
.forEach(key => {
results[key] = results[key] || {};
results[key][file['.file']] = prepStats(file[key]);
});
});
}

const table = new Table();
table.push(
Expand All @@ -78,37 +78,36 @@ table.push(
stats.reduce(arr => arr.concat(fileNames), ['args'])
);

Object.keys(results)
.forEach(key => {
table.push(stats.reduce((arr, stat) => {
let min = Infinity;
let max = -Infinity;

const statGroup = fileNames.map(fileName => {
let result = results[key][fileName];
result = result && result[stat];

if (result) {
min = Math.min(min, result);
max = Math.max(max, result);
return result;
}

return '';
});

return arr.concat(statGroup.map(stat => {
if (stat === min) {
return chalk.green(stat);
}

if (stat === max) {
return chalk.red(stat);
}

return stat;
}));
}, [key]));
});
for (const key of Object.keys(results)) {
table.push(stats.reduce((arr, stat) => {
let min = Infinity;
let max = -Infinity;

const statGroup = fileNames.map(fileName => {
let result = results[key][fileName];
result = result && result[stat];

if (result) {
min = Math.min(min, result);
max = Math.max(max, result);
return result;
}

return '';
});

return arr.concat(statGroup.map(stat => {
if (stat === min) {
return chalk.green(stat);
}

if (stat === max) {
return chalk.red(stat);
}

return stat;
}));
}, [key]));
}

console.log(table.toString());
4 changes: 2 additions & 2 deletions docs/recipes/when-to-use-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ In most cases, it's a bad idea to use any complex branching inside your tests. A
```js
const testData = require('./fixtures/test-definitions.json');

testData.forEach(testDefinition => {
for (const testDefinition of testData) {
test('foo or bar', t => {
const result = functionUnderTest(testDefinition.input);

Expand All @@ -134,7 +134,7 @@ testData.forEach(testDefinition => {
t.is(result.bar, testDefinition.foo);
}
});
});
}
```

## Conclusion
Expand Down
14 changes: 7 additions & 7 deletions lib/ava-files.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ class AvaFiles {
const overrideDefaultIgnorePatterns = [];

let hasPositivePattern = false;
this.sources.forEach(pattern => {
for (const pattern of this.sources) {
mixedPatterns.push(pattern);

// TODO: Why not just `pattern[0] !== '!'`?
Expand All @@ -168,10 +168,10 @@ class AvaFiles {

// Extract patterns that start with an ignored directory. These need to be
// rematched separately.
if (defaultIgnore.indexOf(pattern.split('/')[0]) >= 0) {
if (defaultIgnore.includes(pattern.split('/')[0])) {
overrideDefaultIgnorePatterns.push(pattern);
}
});
}

// Same defaults as used for Chokidar
if (!hasPositivePattern) {
Expand All @@ -182,7 +182,7 @@ class AvaFiles {

// Ignore paths outside the current working directory.
// They can't be matched to a pattern.
if (/^\.\.\//.test(filePath)) {
if (filePath.startsWith('../')) {
return false;
}

Expand Down Expand Up @@ -255,21 +255,21 @@ class AvaFiles {
let paths = [];
let ignored = [];

this.sources.forEach(pattern => {
for (const pattern of this.sources) {
if (pattern[0] === '!') {
ignored.push(pattern.slice(1));
} else {
paths.push(pattern);
}
});
}

// Allow source patterns to override the default ignore patterns. Chokidar
// ignores paths that match the list of ignored patterns. It uses anymatch
// under the hood, which supports negation patterns. For any source pattern
// that starts with an ignored directory, ensure the corresponding negation
// pattern is added to the ignored paths.
const overrideDefaultIgnorePatterns = paths
.filter(pattern => defaultIgnore.indexOf(pattern.split('/')[0]) >= 0)
.filter(pattern => defaultIgnore.includes(pattern.split('/')[0]))
.map(pattern => `!${pattern}`);

ignored = getDefaultIgnorePatterns().concat(ignored, overrideDefaultIgnorePatterns);
Expand Down
2 changes: 1 addition & 1 deletion lib/serialize-error.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function buildSource(source) {
const rel = path.relative(projectDir, file);

const isWithinProject = rel.split(path.sep)[0] !== '..';
const isDependency = isWithinProject && path.dirname(rel).split(path.sep).indexOf('node_modules') > -1;
const isDependency = isWithinProject && path.dirname(rel).split(path.sep).includes('node_modules');

return {
isDependency,
Expand Down
12 changes: 6 additions & 6 deletions lib/watcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class TestDependency {
}

contains(source) {
return this.sources.indexOf(source) !== -1;
return this.sources.includes(source);
}
}

Expand All @@ -97,7 +97,7 @@ class Watcher {

let runOnlyExclusive = false;
if (specificFiles) {
const exclusiveFiles = specificFiles.filter(file => this.filesWithExclusiveTests.indexOf(file) !== -1);
const exclusiveFiles = specificFiles.filter(file => this.filesWithExclusiveTests.includes(file));
runOnlyExclusive = exclusiveFiles.length !== this.filesWithExclusiveTests.length;
if (runOnlyExclusive) {
// The test files that previously contained exclusive tests are always
Expand Down Expand Up @@ -294,21 +294,21 @@ class Watcher {
sumPreviousFailures(beforeVector) {
let total = 0;

this.filesWithFailures.forEach(state => {
for (const state of this.filesWithFailures) {
if (state.vector < beforeVector) {
total += state.count;
}
});
}

return total;
}

cleanUnlinkedTests(unlinkedTests) {
unlinkedTests.forEach(testFile => {
for (const testFile of unlinkedTests) {
this.updateTestDependencies(testFile, []);
this.updateExclusivity(testFile, false);
this.pruneFailures([testFile]);
});
}
}

observeStdin(stdin) {
Expand Down
4 changes: 2 additions & 2 deletions lib/worker/dependency-tracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function track(filename) {
exports.track = track;

function install(testPath) {
Object.keys(require.extensions).forEach(ext => {
for (const ext of Object.keys(require.extensions)) {
const wrappedHandler = require.extensions[ext];

require.extensions[ext] = (module, filename) => {
Expand All @@ -38,6 +38,6 @@ function install(testPath) {

wrappedHandler(module, filename);
};
});
}
}
exports.install = install;
16 changes: 8 additions & 8 deletions lib/worker/subprocess.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ runner.on('finish', () => {
}

nowAndTimers.setImmediate(() => {
currentlyUnhandled().filter(rejection => {
return !attributedRejections.has(rejection.promise);
}).forEach(rejection => {
ipc.send({type: 'unhandled-rejection', err: serializeError('Unhandled rejection', true, rejection.reason)});
});
currentlyUnhandled()
.filter(rejection => !attributedRejections.has(rejection.promise))
.forEach(rejection => {
ipc.send({type: 'unhandled-rejection', err: serializeError('Unhandled rejection', true, rejection.reason)});
});

exit(0);
});
Expand Down Expand Up @@ -103,15 +103,15 @@ dependencyTracking.install(testPath);
precompilerHook.install();

try {
(options.require || []).forEach(x => {
const required = require(x);
for (const mod of (options.require || [])) {
const required = require(mod);

try {
if (required[Symbol.for('esm\u200D:package')]) {
require = required(module); // eslint-disable-line no-global-assign
}
} catch (_) {}
});
}

require(testPath);

Expand Down
14 changes: 3 additions & 11 deletions test/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -627,18 +627,10 @@ test('caching is enabled by default', t => {
return api.run([path.join(__dirname, 'fixture/caching/test.js')])
.then(() => {
const files = fs.readdirSync(path.join(__dirname, 'fixture/caching/node_modules/.cache/ava'));
t.is(files.filter(x => endsWithJs(x)).length, 1);
t.is(files.filter(x => endsWithMap(x)).length, 1);
t.is(files.filter(x => x.endsWith('.js')).length, 1);
t.is(files.filter(x => x.endsWith('.map')).length, 1);
t.is(files.length, 2);
});

function endsWithJs(filename) {
return /\.js$/.test(filename);
}

function endsWithMap(filename) {
return /\.map$/.test(filename);
}
});

test('caching can be disabled', t => {
Expand Down Expand Up @@ -702,7 +694,7 @@ test('emits dependencies for test files', t => {
api.on('run', plan => {
plan.status.on('stateChange', evt => {
if (evt.type === 'dependencies') {
t.notEqual(testFiles.indexOf(evt.testFile), -1);
t.true(testFiles.includes(evt.testFile));
t.strictDeepEqual(evt.dependencies.slice(-3), sourceFiles);
}
});
Expand Down
2 changes: 1 addition & 1 deletion test/fixture/debug-arg.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import test from '../..';

test('test', t => {
t.true(process.execArgv[0].indexOf('--debug') === 0);
t.true(process.execArgv[0].startsWith('--debug'));
});
2 changes: 1 addition & 1 deletion test/fixture/inspect-arg.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import test from '../..';

test('test', t => {
t.true(process.execArgv[0].indexOf('--inspect') === 0);
t.true(process.execArgv[0].startsWith('--inspect'));
});
4 changes: 2 additions & 2 deletions test/integration/assorted.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ test('--match works', t => {
});
});

['--tap', '-t'].forEach(tapFlag => {
for (const tapFlag of ['--tap', '-t']) {
test(`${tapFlag} should produce TAP output`, t => {
execCli([tapFlag, 'test.js'], {dirname: 'fixture/watcher'}, err => {
t.ok(!err);
t.end();
});
});
});
}

test('handles NODE_PATH', t => {
const nodePaths = `fixture/node-paths/modules${path.delimiter}fixture/node-paths/deep/nested`;
Expand Down
22 changes: 12 additions & 10 deletions test/integration/concurrency.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,53 @@
const test = require('tap').test;
const {execCli} = require('../helper/cli');

['--concurrency', '-c'].forEach(concurrencyFlag => {
const concurrencyFlags = ['--concurrency', '-c'];

for (const concurrencyFlag of concurrencyFlags) {
test(`bails when ${concurrencyFlag} is provided without value`, t => {
execCli(['test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
t.is(err.code, 1);
t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
t.end();
});
});
});
}

['--concurrency', '-c'].forEach(concurrencyFlag => {
for (const concurrencyFlag of concurrencyFlags) {
test(`bails when ${concurrencyFlag} is provided with an input that is a string`, t => {
execCli([`${concurrencyFlag}=foo`, 'test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
t.is(err.code, 1);
t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
t.end();
});
});
});
}

['--concurrency', '-c'].forEach(concurrencyFlag => {
for (const concurrencyFlag of concurrencyFlags) {
test(`bails when ${concurrencyFlag} is provided with an input that is a float`, t => {
execCli([`${concurrencyFlag}=4.7`, 'test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
t.is(err.code, 1);
t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
t.end();
});
});
});
}

['--concurrency', '-c'].forEach(concurrencyFlag => {
for (const concurrencyFlag of concurrencyFlags) {
test(`bails when ${concurrencyFlag} is provided with an input that is negative`, t => {
execCli([`${concurrencyFlag}=-1`, 'test.js', concurrencyFlag], {dirname: 'fixture/concurrency'}, (err, stdout, stderr) => {
t.is(err.code, 1);
t.match(stderr, 'The --concurrency or -c flag must be provided with a nonnegative integer.');
t.end();
});
});
});
}

['--concurrency', '-c'].forEach(concurrencyFlag => {
for (const concurrencyFlag of concurrencyFlags) {
test(`works when ${concurrencyFlag} is provided with a value`, t => {
execCli([`${concurrencyFlag}=1`, 'test.js'], {dirname: 'fixture/concurrency'}, err => {
t.ifError(err);
t.end();
});
});
});
}
Loading