Skip to content

Commit

Permalink
Add a mostly hidden test.default that provides test
Browse files Browse the repository at this point in the history
Our type definition uses ESM syntax; when using CJS with VSCode, the
auto-completion assumes the root is accessed through `require('ava').default`.
Placate VSCode by adding a mostly hidden default property on the root. This is
available through both CJS and ESM imports. We use a proxy so that we don't end
up with root.default.default.default chains.

Fixes #2539.
  • Loading branch information
novemberborn committed Sep 18, 2021
1 parent 87929b4 commit 8b25d05
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/create-chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,5 +101,28 @@ export default function createChain(fn, defaults, meta) {

root.meta = meta;

// Our type definition uses ESM syntax; when using CJS with VSCode, the
// auto-completion assumes the root is accessed through `require('ava').default`.
// Placate VSCode by adding a mostly hidden default property on the root.
// This is available through both CJS and ESM imports. We use a proxy so that
// we don't end up with root.default.default.default chains.
Object.defineProperty(root, 'default', {
configurable: false,
enumerable: false,
writable: false,
value: new Proxy(root, {
apply(target, thisArg, argumentsList) {
target.apply(thisArg, argumentsList);
},
get(target, prop) {
if (prop === 'default') {
throw new TypeError('Cannot access default.default');
}

return target[prop];
},
}),
});

return root;
}
7 changes: 7 additions & 0 deletions test/cjs-default/fixtures/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"ava": {
"files": [
"*.cjs"
]
}
}
19 changes: 19 additions & 0 deletions test/cjs-default/fixtures/test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const test = require('ava');

test.default('callable', t => { // eslint-disable-line ava/no-unknown-modifiers
t.pass();
});

test('no recursion', t => {
t.throws(() => test.default.default, {
name: 'TypeError',
});
});

test('not enumerable', t => {
t.false(Object.keys(test).includes('default'));
});

test('main export equals the ESM export', async t => {
t.is(test, (await import('ava')).default); // eslint-disable-line node/no-unsupported-features/es-syntax
});
7 changes: 7 additions & 0 deletions test/cjs-default/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import test from '@ava/test';

import {fixture} from '../helpers/exec.js';

test('ok', async t => {
await t.notThrowsAsync(fixture());
});

0 comments on commit 8b25d05

Please sign in to comment.