salesforce / sfdx-lwc-jest

Run Jest against LWC components in SFDX workspace environment
MIT License
165 stars 82 forks source link

Description for mocking external components may be wrong #285

Closed azizk closed 1 year ago

azizk commented 2 years ago

Description

Steps to Reproduce

The README describes how to mock external components, but in my case for lightning/primitiveIcon it doesn't work. It works if you provide the full path to the js file in the mapped module path in jest.config.js.

// The test function is not really relevant
<!-- /force-app/stdlib/jest-mocks/lightning/primitiveIcon.html -->
<template></template>
// /force-app/stdlib/jest-mocks/lightning/primitiveIcon.js
import { api, LightningElement } from "lwc";

export default class PrimitiveIcon extends LightningElement {
  @api iconName;
  @api size;
  @api svgClass;
  @api variant;
}
const { jestConfig } = require("@salesforce/sfdx-lwc-jest/config");
module.exports = {
  ...jestConfig,
  modulePathIgnorePatterns: ["<rootDir>/.localdevserver"],
  moduleNameMapper: {
    "^lightning/(primitiveIcon)$":
      "<rootDir>/force-app/stdlib/jest-mocks/lightning/$1"
  },
  collectCoverage: true,
  coverageReporters: ["cobertura", "text"]
};
sfdx-lwc-jest --coverage

Expected Results

Should not throw a configuration error.

Actual Results

  ● Test suite failed to run

    Configuration error:

    Could not locate module lightning/primitiveIcon mapped as:
    /home/work/src/project/force-app/stdlib/jest-mocks/lightning/$1.

    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^lightning\/(primitiveIcon)$/": "/home/work/src/project/force-app/stdlib/jest-mocks/lightning/$1"
      },
      "resolver": /home/work/src/project/node_modules/@salesforce/sfdx-lwc-jest/src/resolver.js
    }

      at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:900:17)
      at Object.<anonymous> (force-app/stdlib/lwc/button/button.html.compiled:5:1)

Version

Possible Solution

The solution is to add the js file name to the mapped module path:

module.exports = {
  ...,
  moduleNameMapper: {
    "^lightning/(primitiveIcon)$":
      "<rootDir>/force-app/stdlib/jest-mocks/lightning/$1/$1.js"
  }
};
azizk commented 1 year ago

Closing due to inactivity.