December 17, 2020
TestsSource
- Tests
- Top level await - How to test it?
Source Code
The source code we wrote during the event.
fast.js
await new Promise((resolve) => {
setTimeout(resolve, 10);
});
export default 'fast-file';
dynamic-import.spec.js
import {strict as assert} from 'assert';
const fastestFile = await Promise.any([
import('./slow.js'),
import('./not-existing.js'),
import('./fast.js'),
]);
it('fastest import in a top level await wins', () => {
assert.equal(fastestFile.default, 'fast-file');
});
xit('a stringified dynamic import starts with [Module]', async () => {
const fastFile = await import('./fast.js');
assert.equal(fastFile, '[Module] ...');
});
rejection.spec.js
import {strict as assert} from 'assert';
try {
await Promise.reject();
it('a top level that throws can be caught, we should never see this', () => {
assert(false);
});
} catch {
it('a top level that throws can be caught', () => {
assert(true);
});
}
top-level-await.spec.js
import assert from 'assert';
const x = await 1;
describe('Top level await - How to test it?', () => {
it('an await on the top level (see above) had been working', () => {
assert.equal(x, 1);
});
it('an await inside eval throws, because ... (maybe we find out on twitter, #jslang)', () => {
assert.throws(() => { eval('await 1') }, SyntaxError);
});
});
const before = new Date().getTime();
const after = await new Promise((resolve) => {
setTimeout(() => resolve(new Date().getTime()), 3000);
});
it('top level await blocks the execution until it resolves', () => {
assert(before + 2000 < after);
});
slow.js
await new Promise((resolve) => {
setTimeout(resolve, 1000);
});
export default 'slow-file';