I created a function that tries to import a script by a given source, tries to call its exported function and processes the returned result.
For the sake of simplicity I minimized the code and simply return the result
const getResult = async function (source: string): Promise<unknown> {
let resultFunction;
try {
resultFunction = await import(source);
} catch (error) {
// error handling for failed imports
throw error;
}
if (typeof resultFunction !== 'function') {
// error handling if not a function
throw new Error("TODO - not a function");
}
const result = await resultFunction();
return result;
};
export { getResult };
I want to write tests for this function. The first sample file in the test directory is
const syncFn = function () {
return 'sync';
};
export default syncFn;
Next I added a dummy test
import assert from 'assert/strict';
import { getResult } from '../lib/getResult';
import test from 'node:test';
test('getResult', async t => {
await t.test('first test', async () => {
const actualResult = await getResult("../test/samples/syncFn.ts"); // it seems I must use the relative path starting at getResult.ts
assert.equal(actualResult, "sync");
});
});
Sidenotes:
I'm using Node v18.10.0 with the builtin testrunner. The content of the package.json file is
{
"scripts": {
"test": "node --test --require ts-node/register $(find . -name '*Tests.ts')"
},
"dependencies": {
"@types/node": "18.8.0"
},
"devDependencies": {
"ts-node": "10.9.1",
"typescript": "4.8.4"
}
}
and the whole repo structure is
When running npm run test
the test fails because of
TODO - not a function
When inspecting the type of the imported resultFunction
I see that it's an object, although I would expect it to be a function.
Does someone know what's wrong?
CodePudding user response:
The return value of import()
is a promise that resolves to an object.
If you want to get the default exported value you need to:
const { default: resultFunction } = await import(source);