Skip to content

Cannot create a stream then load ESM test modules #575

@ydarma

Description

@ydarma

Hi, the following won't work :

import test from 'tape';

test.createStream({ objectMode: true }).on('data', function (row) {
    console.log(JSON.stringify(row));
});

import('./testESMModule.mjs');
/* ./testESMModule.mjs */

import test from 'tape';

test('This one should pass', function (t) {
    t.pass();
    t.end();
});

Actually the test in the ESM Module does not run because the stream creates a result queue that is exhausted in the same event loop it is created in (results are consumed in a setImmediate callback). The ESM module will be loaded asynchronously, in a subsequent event loop.

The wait and run function used in the cli are not helpful here because the stream will be recreated on the run method, thus :

  • the stream will not be the one with registered listeners.
  • the tests are not registered on the stream because the run method is called after the test are defined in the test module.

For now I am using this trick :

import test from 'tape';

test.createStream({ objectMode: true }).on('data', function (row) {
    console.log(JSON.stringify(row));
});

test('__load_async__', async function (t) {
    await import('./testESMModule.mjs');
    t.end();
});

The result processing starts by the synchronously defined test named '__load_async__' in the same event loop in which the stream is created. It will then "lock" the stream until all modules are loaded (because t.end() is called once they're all loaded). Then the results processing continues with the asynchronously defined tests.

I propose something better, which implementation uses the same kind of mechanism as above :

import test from 'tape';

test.createStream({ objectMode: true }).on('data', function (row) {
    console.log(JSON.stringify(row));
});

test.async(async function () {
    await import('./testESMModule.mjs');
});

I implemented this here : https://github.com/ydarma/tape/blob/async-load/test/async-test-load.js (I can make a PR).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions