Search code examples
node.jstypescriptwebpackcypresse2e-testing

Cypress - Error: Can't resolve 'async_hooks'


Current behavior

I know this kind of issue was fixed in the version 5.1.0 but ...

I'm trying to seed DB in the Node JS part logic at the before hook We have the cls-hooked and 1 more internal npm module for sharing both use async_hooks When I'm trying to import and use any of that modules I receive crashes at the test script launch:

Error: Webpack Compilation Error
./node_modules/...[our private module name].../lib/...[file name]....js
Module not found: Error: Can't resolve 'async_hooks' in '/Users/.../node_modules/...[private module or cls-hooked].../lib'
resolve 'async_hooks' in '/Users/.../node_modules/...[private module or cls-hooked].../lib'
  Parsed request is a module
  using description file: /Users/.../node_modules/...[private module or cls-hooked].../package.json (relative path: ./lib)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module

Desired behavior

Test script launch should go smoothly with before hook executing

Test code to reproduce

require some module in ./cypress/plugins/index.ts with next similar logic

var async_hooks = require("async_hooks");
var asyncLocalStorage = new async_hooks.AsyncLocalStorage();
...
asyncLocalStorage.getStore();

Cypress Version

^8.1.0 - 8.5.0

Cypress binary version: 8.5.0
Electron version: 13.2.0
Bundled Node version: 14.16.0

tried Node version: 14.17.6 and 16.9.1

the same for:

Cypress binary version: 7.7.0
Electron version: 12.0.0-beta.14
Bundled Node version: 14.15.1

Other

additional install of "async_hooks": "^1.0.0" didn't help

Using TS "typescript": "^4.1.5" OS macOS Big Sur 11.16


Solution

  • The problem was in 1 common file for both processes browser and NodeJs in Cypress. In this case, Webpack built the bundle with 'browser' context but received NodeJs context logic. That's why the error occured. When I used enum in Browser part in the file which besides that also exports NodeJs logic it (Webpack) didn't make the 'treeshaking', thus the NodeJs logic was imported into the bundle for browser process logic. 🤷‍♂️