salesforce / sfdx-lwc-jest

Run Jest against LWC components in SFDX workspace environment
MIT License
164 stars 81 forks source link

How to configure jest to use mocks from node_modules from external 2gp dependencies #305

Closed joeythomaschaske closed 1 year ago

joeythomaschaske commented 1 year ago

Description

I am a package developer and have multiple 2gp packages contained in their own separate repos. These packages form dependencies.

If a package contains LWCs I would like to publish mocks via npm so that other managed packages that depend on it can use them if they use the components from the package.

I am running into errors attempting to configure jest to use the mocks that are located in node_modules when the package is installed

Additionally, I have requested an example of how to do this correctly in the LWC Recipes repo

Steps to Reproduce

Example jest.config.js:

const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
  ...jestConfig,
  roots: ['<rootDir>/force-app/main/default/lwc'],
  moduleNameMapper: {
    '^c/uiMessage$': '<rootDir>/node_modules/@komodohealth/p-pltfm-core/__mocks__/uiMessage.js',
  },
};

Expected Results

Jest uses the mock from node_modules

Actual Results

User@User tx-fnds-mvn-content % yarn test:lwc cmOfficeFileSelector
yarn run v1.22.19
$ ./node_modules/.bin/sfdx-lwc-jest -- cmOfficeFileSelector
error Invalid sourceApiVersion found in sfdx-project.json. Expected 57.0, found 56.0
 FAIL  force-app/main/default/lwc/cmOfficeFileSelector/__tests__/cmOfficeFileSelector.test.js
  ● Test suite failed to run

    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

    Details:

    /Users/User/dev/Foundations/tx-fnds-mvn-content/node_modules/@komodohealth/p-pltfm-core/__mocks__/uiMessage.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { api, LightningElement } from 'lwc';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (force-app/main/default/lwc/cmOfficeFileSelector/cmOfficeFileSelector.html.compiled:8:1)
      at Object.<anonymous> (force-app/main/default/lwc/cmOfficeFileSelector/src/cmOfficeFileSelector.ts:2:31)
      at Object.<anonymous> (force-app/main/default/lwc/cmOfficeFileSelector/src/__tests__/cmOfficeFileSelector.test.ts:3:1)
      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)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.769 s
Ran all test suites matching /cmOfficeFileSelector/i.

Version

Additional context/Screenshots

node_modules content:

Screenshot 2023-03-13 at 5 46 41 PM

node_modules/@komodohealth/p-pltfm-core/__mocks__/uiMessage.js contents:

import { api, LightningElement } from 'lwc';
export default class UiMessage extends LightningElement {
  @api
  message;
  @api
  iconName = 'utility:info';
  @api
  iconVariant;
  @api
  iconSize = 'small';
}
joeythomaschaske commented 1 year ago

Ok I think I figured it out, in my jest.config.js I wasn't setting transformIgnorePatterns to ignore everything but my npm package with my mocks.

However, there's not a good way to add my npm packages to this with out also including what sfdx-lwc-jest has in its base jest config

transformIgnorePatterns: [
    '/node_modules/(?!(.*@salesforce/sfdx-lwc-jest/src/lightning-stubs)/)',
],

So I have to manually include this, which means if the source config changes it could cause problems

transformIgnorePatterns: [
  '/node_modules/(?!(.*@salesforce/sfdx-lwc-jest/src/lightning-stubs|@komodohealth)/)'
],
joeythomaschaske commented 1 year ago

Additionally, someone on my team notified me about "Plug n Play" modules which is an entirely different format for storing external dependencies. They warned reaching into node_modules probably won't work with pnp modules.

sfdx-lwc-jest reaches into node_modules today, will this break using plug n play?

nolanlawson commented 1 year ago

This sounds like a question, so I think this issue can be closed. Please reopen if I'm mistaken.

I haven't tested plug n play personally, but in general, I would expect it to not be compatible with everything in the Node.js ecosystem, and there may be something in sfdx-lwc-jest that is incompatible, yes.