vmware-clarity / core

Clarity is a scalable, accessible, customizable, open-source design system built with web components. Works with any JavaScript framework, created for enterprises, and designed to be inclusive.
https://clarity.design
MIT License
163 stars 42 forks source link

Problem importing Clarity components in Jest Unit Tests #194

Closed ngfelixl closed 1 year ago

ngfelixl commented 1 year ago

Describe the bug

When working with Angular in an NX workspace and writing unit tests with Jest I can not import Clarity components without braking the tests.

How to reproduce

I am using an NX workspace with Angular preset and install @cds packages.

npx create-nx-workspace@latest
npm i @cds/{core,angular} --legacy-peer-deps

Then, if a clarity component is part of a Jest unit test, for example:

import { TestBed } from '@angular/core/testing';
import { CdsButtonModule } from '@cds/angular';                                   // <---
import { AppComponent } from './app.component';
import { NxWelcomeComponent } from './nx-welcome.component';

describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [CdsButtonModule],                                                 // <---
      declarations: [AppComponent, NxWelcomeComponent],
    }).compileComponents();
  });
});

It is throwing:

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

/PATHTO/clarity-jest-test/node_modules/@cds/core/accordion/register.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import{registerElementSafely as o,ClarityMotion as r,AnimationAccordionPanelOpenName as c,AnimationAccordionPanelOpenConfig as e}from"@cds/core/internal";import{CdsAccordion as n}from"./accordion.element.js";import{CdsAccordionPanel as d}from"./accordion-panel.element.js";import{CdsAccordionContent as t}from"./accordion-content.element.js";import{CdsAccordionHeader as i}from"./accordion-header.element.js";import"@cds/core/icon/register.js";import"@cds/core/button-expand/register.js";o("cds-accordion",n),o("cds-accordion-panel",d),o("cds-accordion-content",t),o("cds-accordion-header",i),r.add(c,e);
                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1796:14)

Here is a demo repository https://github.com/ngfelixl/clarity-jest-test

Expected behavior

I would expect that the components can be used and imported in Jest unit tests.

Versions

Clarity project:

Clarity version:

Framework:

Framework version:

"@angular/core": "14.0.5",
"@cds/angular": "6.1.4",
"@cds/core": "6.1.4",
"@nrwl/jest": "14.4.2",
"jest": "27.5.1",
"jest-preset-angular": "11.1.2",

Device:

bbogdanov commented 1 year ago

Hi @ngfelixl,

Take a look at the discussion and the solution here -> https://github.com/vmware/clarity/issues/6310

Let us know if the solution didn't work and what happened so we can investigate it.

ngfelixl commented 1 year ago

Hi @bbogdanov,

thanks for the suggestion. However when I change the transformIgnorePatterns in the example repository in /apps/app/jest.config.ts to

transformIgnorePatterns: [
  'node_modules/(?!(@cds|@lit|lit|ramda|.*\\.mjs$))'
],

I receive a different output. But still not working. When I run the testing command it says:

> npx nx run-many --target=test --all --skip-nx-cache

    ✖  nx run app:test
 FAIL   app  apps/app/src/app/app.component.spec.ts
  ● Test suite failed to run

           ENOENT: no such file or directory, open 'PATHTO/clarity-jest-test/node_modules/@cds/core/index.jsicon/shapes/angle.js'

             at Runtime.readFile (../../node_modules/jest-runtime/build/index.js:2574:21)

Test Suites: 1 failed, 1 total
       Tests:       0 total
       Snapshots:   0 total
       Time:        0.965 s
       Ran all test suites.

NX sets up the repository with the Jest types as suggested in the linked thread. I've found several threads for this issue so far and all say that it's related to the transformIgnorePatterns, however none solved it for Clarity+Angular+NX+Jest for me so far.

ngfelixl commented 1 year ago

Happy new year everyone! Unfortunately, I could not find any solutions. @bbogdanov do you have any additional ideas? Thank you!

wghglory commented 1 year ago

I met the same issue.

wghglory commented 1 year ago

@ngfelixl I think I found a solution. You can take a look at https://github.com/wghglory/nx-vmware/blob/main/apps/seed/jest.config.ts. The key thing is to map @cds/core/icon. Please let me know.

moduleNameMapper: {
    '@cds/core/icon/(.*)$': '<rootDir>/../../node_modules/@cds/core/icon/index.js',
 }
ngfelixl commented 1 year ago

Hey @wghglory thank you! Unfortunately, the repository seems to be private. Only with the moduleNameMapper in the jest.config.ts it does not work. What did you do with the transformIgnorePatterns?

wghglory commented 1 year ago

@ngfelixl I just changed it to public. Yes, only moduleNameMapper won't work. The transformIgnorePatterns code is below:

transformIgnorePatterns: ['node_modules/(?!(@cds|@lit|lit|ramda|.*\\.mjs$))'],

My workspace doesn't install @cds/angular, but since @clr/angular now also uses @cds/core/icon, I feel the solution is similar.

ngfelixl commented 1 year ago

Heyhey,

the solution works with Jest 28. In the demo repository we've used Jest 28, however in our real repo we've used Jest 27. So the combination of

works. Still one remark: The transformIgnorePattern might be wrong as the "or" includes any mjs files (see |.*).

github-actions[bot] commented 1 year ago

Hi there 👋, this is an automated message. To help Clarity keep track of discussions, we automatically lock closed issues after 14 days. Please look for another open issue or open a new issue with updated details and reference this one as necessary.