Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem importing Clarity components in Jest Unit Tests #194

Closed
4 of 8 tasks
ngfelixl opened this issue Nov 24, 2022 · 9 comments
Closed
4 of 8 tasks

Problem importing Clarity components in Jest Unit Tests #194

ngfelixl opened this issue Nov 24, 2022 · 9 comments

Comments

@ngfelixl
Copy link

ngfelixl commented Nov 24, 2022

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 Core
  • Clarity Angular/UI

Clarity version:

  • v5.x
  • v6.x

Framework:

  • Angular
  • React
  • Vue
  • Other:

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:

  • Type: Macbook
  • OS: macOS Monterey
@bbogdanov
Copy link
Contributor

Hi @ngfelixl,

Take a look at the discussion and the solution here -> vmware-archive/clarity#6310

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

@ngfelixl
Copy link
Author

ngfelixl commented Nov 28, 2022

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
Copy link
Author

ngfelixl commented Jan 2, 2023

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

@wghglory
Copy link
Contributor

wghglory commented Jan 3, 2023

I met the same issue.

@wghglory
Copy link
Contributor

wghglory commented Jan 3, 2023

@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
Copy link
Author

ngfelixl commented Jan 3, 2023

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
Copy link
Contributor

wghglory commented Jan 3, 2023

@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
Copy link
Author

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

  • Jest 28
  • transformIgnorePatterns: ['node_modules/(?!(@cds|@lit|lit|ramda|.*\\.mjs$))']
  • moduleNameMapper: { '@cds/core/icon/(.*)$': '<rootDir>/../../node_modules/@cds/core/icon/index.js' }

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

@github-actions
Copy link

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.

@github-actions github-actions bot locked and limited conversation to collaborators Jan 26, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants