Skip to content

Apex Mocking

This configuration allows you to mock apex methods without having to explicitly map all files in your lwr.config.json|lwc.config.json file.

There are two approaches to mocking apex classes:

  1. Create a single JavaScript file for each Apex Class (e.g. MyClass.js)
  2. Create a single JavaScript file for each Apex Method (e.g. MyClass.myMethod.js)

Single JavaScript file per Apex Class

This is a cleaner approach and keeps your file system cleaner, at the expense of potentially longer JavaScript files.

This approach uses a custom module provider, which can be configured in your lwr.config.json|lwc.config.json file as follows:

lwr.config.json
"moduleProviders": [
[
"@lwc-garden/utils/resolvers/apex.ts",
{
"paths": ["apex"]
}
],
]

Noting you are able to split up your apex code into multiple folders to better organise your files.

Here is an example of what a MyClass.js file might look like:

apex/MyClass.js
export const myMethod = () => {
// TODO: custom logic here - you may even wish to call Salesforce directly here via fetch
return 'response text'
}
export const anotherMethodHere = ({ properties }) => {
// TODO: custom logic here
return `another piece of response text ${properties}`
}

The above methods an then be imported using the standard apex import syntax:

import apex_myMethod from '@salesforce/apex/MyClass.myMethod'
import apex_anotherMethodHere from '@salesforce/apex/MyClass.anotherMethodHere'

Single JavaScript file per Apex Method

This approach may align more closely with existing mocking approaches and result in smaller JavaScript files at the expense of more files in the file system.

This approach uses a custom hook, which can be configured in your lwr.config.json|lwc.config.json file as follows:

lwr.config.json
"moduleProviders": [
[
"@lwc-garden/utils/hooks/apex.ts",
{
"paths": ["apex"]
}
],
]

Under the hood this hook creates mapping for all apex classes found in the provided "paths" configuration array. Here is an example of what is generated:

lwr.config.json
[
{
"name": "@salesforce/apex/MyClass.myMethod",
"path": "./apex/MyClass.myMethod.js"
}
]