'Object destructuring assignment works with Node but not with Jest

'Using the Playwright Library [1.21.0] with Jest [27.5.1] to run browser automation tests on Node.js [14.18.2].

ESM is the current module format.

// package.json
...
"type": "module",
...

I setup a quick test with the following code:

// playwright-hello.js

import {chromium} from 'playwright';

async function main() {
  const browser = await chromium.launch();

  const page = await browser.newPage();

  await page.goto('http://www.example.com');
  await page.screenshot({ path: 'screenshot.png' });

  await browser.close();
}

main().catch(console.error);

The above code works via CLI command node playwright-hello with no issues.

However, when I try to run similar code with Jest, I get the following error:

 FAIL  test/index.test.js
  ● Test suite failed to run

    SyntaxError: The requested module 'playwright' does not provide an export named 'chromium'

      at Runtime.linkAndEvaluateModule (node_modules/jest-runtime/build/index.js:779:5)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)

I fixed this by updating the test code to use the default export instead:

// changed to use default export instead of named one
import playwright from 'playwright';

// prepended `playwright.` to initial `chromium.launch()`
const browser = await playwright.chromium.launch();

How come the object destructuring assignment in playwright-hello.js [i.e. import {chromium}...] works with node.js CLI, but not with Jest? In other words, node.js did not complain about playwright library not providing a named export, why?

Note: I'm running Jest as follows for ES6 modules support:

NODE_OPTIONS='--experimental-vm-modules' npx jest ./test/index


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source