facebook / yoga

Yoga is an embeddable layout engine targeting web standards.
https://yogalayout.dev/
MIT License
17.22k stars 1.42k forks source link

[JS] Using Yoga npm version 3.0.1 with Jest #1688

Open Omxjep3434 opened 3 weeks ago

Omxjep3434 commented 3 weeks ago

Report

I was wondering if you could provide guidance for how to use Yoga with Jest. I looked at the configuration in 'javascript' folder of the Yoga repo, and I'm not sure how it's working with top-level-await. My guess is that this has something to do with the 'Just' package and configuration? I'm not familiar with that and I'm wondering if there is guidance you can provide using Jest only.

Using async loading via 'yoga-layout/load' Jest initially errors because of the 'import.meta.url' statement. I was able to resolve this by using the "babel-plugin-transform-import-meta" package. Is this the only solution or are you aware of a better solution?

Using sync loading via 'yoga-layout' I am not aware of any way to get Jest to work with top-level-await and successfully import the Yoga object from the "yoga-layout" endpoint. When importing, I see an error message of "await is not defined". Is there any guidance to get this to work, and is there a certain Node version that must be used?

Environment Jest: 29.7.0 @babel/preset-env: 7.25.3 babel-jest: 29.7.0

// babel.config.cjs
module.exports = {
  presets: ['@babel/preset-env'],
  plugins: ["babel-plugin-transform-import-meta"]
};
// jest.config.js
const esModules = ["yoga-layout"].join("|");

export default {
  "testPathIgnorePatterns": ["<rootDir>/node_modules/"],
  "transformIgnorePatterns": [`/node_modules/(?!${esModules})`]
};
NickGerleman commented 2 weeks ago

Jest initially errors because of the 'import.meta.url' statement

That sounds like something in your setup (maybe just preset-env) is transpiling to CommonJS, which may create some problems. If you haven't seen the Jest page for ESModules, it is helpful. https://jestjs.io/docs/ecmascript-modules I don't know how interop would work if you transform some code to CommonJS, but leave other node modules not transformed.

To provide some context on how Yoga repo uses Jest:

  1. We babel transform everything (Yoga and tests), with the same transform we use when publishing/distributing Yoga. This transform is very light (mostly just type strippping) and does not e.g. transform to CommonJS
  2. We need to use Node module loader which is compatible with es modules (so, experimental until Node 22 or 24?). This is a general limitation if you want to use a transform at the same time as ES modules.
NickGerleman commented 2 weeks ago

See here for how we configure transforms/Babel (config is picked up automatically by Jest): https://github.com/facebook/yoga/blob/main/javascript/babel.config.cjs

I think the magic might be modules: false