April 29, 2019

Error: Function ISCHANGED may not be used in this type of formula

Usually this error happens when the workflow evaluation criteria is not "when a record is: created, and every time it’s edited".

ISCHANGED  function is available only in:

1. Assignment rules
2. Validation rules
3. Field updates
4. Workflow rules if the evaluation criteria is set to Evaluate the rule when a record is: created, and every time it’s edited .
5. Formula criteria for executing actions in Process Builder.
6. This function returns FALSE when evaluating any field on a newly created record.
7. If a text field was previously blank, this function returns TRUE when it contains any value.
8. For number, percent, or currency fields, this function returns TRUE when:
a. The field was blank and now contains any value
b. The field was zero and now is blank
c. The field was zero and now contains any other value

How to find the Limits in Salesforce Org real quick?

Run the below code in Anonymous window.

Sample Code:

  1. for ( OrgLimit o : OrgLimits.getAll() ) {  
  2.       
  3.     system.debug( o.getName() + ' - ' + o.getValue() + ' - ' + o.getLimit() );  
  4.       
  5. }  

Get the debug log to find the limits.


(OR)

Run the below code in Anonymous window.

Sample Code:

  1. Http h = new Http();  
  2. HttpRequest req = new HttpRequest();  
  3. req.setEndpoint( Url.getOrgDomainUrl().toExternalForm() + '/services/data/v44.0/limits' );  
  4. req.setMethod('GET');  
  5. req.setHeader( 'Authorization''Bearer ' + UserInfo.getSessionId() );  
  6. HttpResponse res = h.send(req);  
  7. system.debug( 'Limits are ' + res.getBody() );  

Get the debug log to find the limits.

Salesforce Summer '19 Release Quick Summary

Monitor Custom Metadata Type Use in System Overview

Understand your current custom metadata type usage pattern to plan for future custom metadata type work. You can now view custom metadata type usage in System Overview. You can get information about the number of custom metadata types and the size of the custom metadata type records used in your org.



Easily Insert Files When Composing a Case-Related Email
Agents can attach files to an email more easily. Files related to a case or attached to an email are collected under Related Files in the file selector. You can add multiple files at once. And the selector prevents you from adding duplicates.



Access Lightning Experience from Safari on iPad Devices (Beta)
Give your users the ability to run the full desktop version of Lightning Experience on their iPad device when they’re away from their desktop or laptop.

Power Up Your Related Lists with Enhanced Related Lists
Take your related lists to the next level. With Enhanced Related Lists, you can show up to 10 columns, resize and sort your columns, perform mass actions, and wrap text.

Keep Record Context When Switching from Salesforce Classic to Lightning Experience
When you switch from Salesforce Classic to Lightning Experience, you land on the same page in Lightning Experience, if it exists. If the same page doesn’t exist in Lightning Experience, you are redirected to your default landing page, which is determined by the org default or your customizations.

Zoom Through Related Lists with Quick Filters
Use quick filters in your related lists to find the data that you’re looking for. Related list quick filters are different from regular list view filters in that they aren’t saved, persist only throughout your current session, and can’t be shared.


Search Picklist Fields in List Views
You don’t have to manually pick through your list views to find the picklist values you’re looking for. List view search now includes picklists in your query results. Dependent picklists and picklists with translated values aren’t searchable.

See More in Item Menus on the Navigation Bar
We increased the number of recent items shown in item menus from three to five. We also made some styling enhancements, including bold section names and separators, to make it easier to tell the different sections apart.

The Lightning Experience Header Is Hidden When You Print from Your Browser
All you want is what’s on the page. The Lightning Experience header, including the search box and navigation bar, is no longer included when you print from your browser.

Current Print View(Shows Search bar)



Summer '19 Print View


Choose from Two Record View Options
Now you have two record page view default options. Choose between the current view—now called Grouped view—and the new Full view. Full view displays all details and related lists on the same page. If you’re transitioning to Lightning Experience, this view is similar to Salesforce Classic.

Make Long-Running Callouts with Continuations
Use the Continuation class in Apex to make a long-running request to an external web service from an Aura component or a Lightning web component. Process the response in a callback method. An asynchronous callout made with a continuation doesn’t count toward the Apex limit of 10 synchronous requests that last longer than five seconds. Therefore, you can make more long-running callouts and integrate your component with a complex back-end API.

Enforce Field-Level Security in Apex (Pilot)
Apex has a new security feature for field-level data protection, which is accessed through the Security and SObjectAccessDecision classes. To ensure secure processing in Apex in the context of the current user’s read, create, or update operation, use the stripInaccessible method. Based on the field-level security of the current user, this method can be used to strip the fields from query results that the user can’t access. The method can also be used to remove inaccessible fields from sObjects before a DML operation to avoid exceptions and to sanitize sObjects that have been deserialized from an untrusted source.

  1. List<Opportunity> opportunities = new List<Opportunity>{  
  2.     new Opportunity(Name='Opportunity1'),  
  3.     new Opportunity(Name='Opportunity2', Probability=95)  
  4. };  
  5.   
  6. // Strip fields that are not creatable  
  7. SObjectAccessDecision decision = Security.stripInaccessible(  
  8.     AccessType.CREATABLE,  
  9.     opportunities);  
  10.   
  11. // Print stripped records  
  12. for (SObject strippedOpportunity : decision.getRecords()) {  
  13.     System.debug(strippedOpportunity);  
  14. }  
  15.   
  16. // print modified indexes  
  17. System.debug(decision.getModifiedIndexes());  
  18.   
  19. // Print removed fields  
  20. System.debug(decision.getRemovedFields());  
  21.   
  22. //System.debug Output  
  23. // DEBUG|Opportunity:{Name=Opportunity1}  
  24. // DEBUG|Opportunity:{Name=Opportunity2}  
  25. // DEBUG|{1}  
  26. // DEBUG|{Opportunity={Probability}}  

Fire Platform Events from Batch Apex Classes (Generally Available)
Batch Apex classes can fire platform events when an error or exception is encountered. A batch Apex class declaration must be using API version 44.0 or later to implement the Database.RaisesPlatformEvents interface and fire a platform event. A platform event record now includes the phase of the batch job (start, execute, or finish) when the error was encountered. The start and finish methods of the Database.Batchable interface now fire platform events on error (which they didn’t do in the beta release).

public with sharing class YourSampleBatchJob implements Database.Batchable<SObject>,
   Database.RaisesPlatformEvents{
   // class implementation
}

Receive Streaming Events in Your Lightning Web Component
In Winter ’19, we introduced the lightning:empApi Aura component for subscribing to event streaming channels in your Aura components. Now you can do the same in your Lightning web components using the lightning/empApi module.

Process Change Event Messages in Apex Triggers
With Apex change event triggers, you can now process change event messages on the Lightning Platform. Change event triggers run asynchronously after the database transaction is completed. Perform resource-intensive business logic asynchronously in the change event trigger and keep transaction-based logic in the Apex object trigger. By decoupling the processing of changes, change event triggers can help reduce transaction processing time.

Work with More Custom Objects in Your Org
We raised the total hard limit for custom objects in an org to 2,500 so that you can install more custom objects from packages. Each Salesforce edition has a specific limit on the number of custom objects that you can create in your org. Beyond the edition limit, the hard limit governs how many custom objects you can install from managed packages, such as apps publicly posted on AppExchange. The new 2,500 limit includes the maximum number of custom objects created and installed in your org.

Path: Celebrate Sales Milestones
Help your teams celebrate their successes. Toss some virtual confetti when reps reach a designated path stage, for example, winning an opportunity. You can choose the frequency, such as always for those hard-won victories or only sometimes for daily occurrences. Celebrations don’t work on the status Converted on leads.



Custom Object Access Settings Default to Private
When you create custom objects, the external access level now defaults to Private if you’ve enabled external org-wide defaults. Previously, the external access level defaulted to Public Read/Write.

Merge Cases into a Single Record (Beta)
If you have duplicate cases or cases that you want to merge into a single case, you can now merge two or three cases into one master record. When you merge cases, the master record is updated with your chosen field values. Most related lists, feed items, and child records are merged into the master record. The master record keeps the Chatter feeds, your values for read-only and hidden fields (except Created Date and Created By), related items, and security.

Get Notified When Reports Conditions Are Met
Don’t wait to find out when an important aggregate in your Salesforce report reaches a meaningful threshold. When a change affects a report that you rely on, report subscribers can receive the updated information right away. For instance, set conditions to send email when average case age is greater than one day, or opportunity count rises above 100. Choose whether the email contains a summary of the conditions that were met or a summary plus the whole report.


Evaluate Each Record in Reports with Row-Level Formulas (Beta)
Answering business questions sometimes means making a calculation on every row in a report. With row-level formulas, you don't need to export report data to a spreadsheet or ask an admin to create a one-off custom formula field. Instead, write a row-level formula directly in the Lightning report builder.



Find Records Faster with Search
Wading through an entire report to find just the records you’re interested in can be time-consuming. The report table search makes its entrance so that you spend less time looking for the information you need.


Find Existing Letterheads in a New Location in Salesforce Classic
Looking for the letterheads that you created in Salesforce Classic? They’re still there in Setup, under the renamed menu option Classic Letterheads.


April 27, 2019

How to subscribe to Salesforce Push Topic from Workbench?

1. Go to https://workbench.developerforce.com/login.php.

2. Log in using the credentials.

3. Go to Queries --> Streaming Push Topics.


4. Select the push topic and click "Subscribe" button.


If you have MuleSoft access, use the below link

http://www.infallibletechie.com/2019/04/how-to-subscribe-to-pushtopic-from.html

How to subscribe to a PushTopic from MuleSoft?

In the below example, whenever Service Contract record is created or updated, it gets the Asset(Custom field) from the Service Contract and updates it's status to Purchased.

Flow:



Subscribe Topic Configuration:



Logger Configuration:



Set Variable Configuration:



Transform Message Configuration:



Salesforce Update Configuration:



Output:



April 25, 2019

Salesforce TLS Login Report

Report:

1. Select Users Report Type.


2. Use TLS in the report filter.



SOQL:

SELECT Name FROM User WHERE Id IN ( SELECT UserId FROM LoginHistory WHERE LoginTime = LAST_N_DAYS:90 AND TlsProtocol IN ( 'TLS 1.0', 'TLS 1.1' ) )

April 23, 2019

Subscribe reports email notification content in Salesforce

On the Schedule Report page, specify a running user who has access to the folder where the report is stored.

The access level of the running user determines what other users, including portal users, see when they receive the scheduled report run results.


April 21, 2019

Component Filter in Lightning Experience

Component Filter in Lightning Experience allows us to define when the lightning component should display/hide.

This helps us to design dynamic lightning pages using App Builder.


Salesforce Interview Questions with Answers Part 55

1. Only Last PushTopic Notification Sent for the Same Record

In API version 36.0 and earlier, when multiple PushTopic notifications are generated for the same record within about one millisecond and in the same transaction, only the last notification is sent.
The other notifications are suppressed because notifications are tracked at the millisecond level. When multiple notifications happen within a transaction at the same time—less than one millisecond—only the last notification can be delivered.

PushTopic notification from Bulk API
Updates performed by the Bulk API won’t generate notifications since such updates could flood a channel.

2. Formula fields in PushTopic Query

Formula fields in WHERE clauses are not supported.

Formula fields are supported in SELECT clauses though.

3. Time dependent process actions in Process Builder

In Process Builder time based actions are available when "only when a record is created" is selected. For "when a record is created or edited", if you select "Do you want to execute the actions only when specified changes are made to the record?" in the criteria then time based actions will appear.

4. Subscribe reports email notification content

On the Schedule Report page, specify a running user who has access to the folder where the report is stored.

The access level of the running user determines what other users, including portal users, see when they receive the scheduled report run results.

5. How to avoid locking contention in Salesforce?

Always sort the file by the lookup / master-detail field that represents the parent record. For example, if loading Contacts, sort by AccountId field to minimize locking contention on the parent records.

6. Transfer Record profile permission

To transfer multiple accounts, campaigns, contacts, contracts, and custom objects:

Transfer Record AND Edit on the object type

To transfer multiple leads:

Transfer Leads OR Transfer Record AND Edit on leads

To transfer multiple cases:

Transfer Cases OR Transfer Record AND Edit on cases

OWD or Sharing Rules or Role Hierarchy won't work since Transfer Record override it.

User with "Transfer Record" permission allowed to transfer ALL records, as long as the user has Edit permission to the object. Read again here "edit on object" NOT "edit on record", this means, the user will be able to transfer record owner even user do not have Edit access to that record.

7. Purpose of comments in coding

The real purpose of comments is to explain “WHY” you did something, not “WHAT” thecode is doing. If you don’t explain this, other programmers may be confused and when they go to change your code they might remove important parts of it.

8. System  and User mode in Salesforce

Trigger runs in System mode. If triggers calls an apex class with sharing keyword, then record level access will be considered.

Validation Rule runs in System mode.

Auto Response Rule runs in System mode.

Assignment Rule runs in System mode.

Workflow Rule runs in System mode.

Escalation Rule runs in System mode.

Formula, Rollup Summary runs in System mode.

Process Builder runs in System mode.

Custom Button runs in System mode.

Visual Workflow or flow runs in User mode.
If flow is called from Process Builder, then runs in System mode.
If flow is called from Workflow, then runs in System mode.
If flow is called from Apex, then runs in (depends on with or without sharing of apex class).
If flow is called from Custom Button, then runs in System mode.
If flow is embed in Visualforce, then runs in VFP context.
If flow is called from REST API, then runs in System mode.

Approval Process runs in System mode.

Publisher Action runs in System mode.

InvocableMethod
If this is called from flow, then runs in User mode.
If this is called from Process Builder (does it depends on with or without sharing is specified on that Class), then runs in System mode.
if this is called from REST API, then runs in (depends on with or without sharing of the class).

Test method with System.runAs() runs in User mode.
Test method without System.runAs() runs in System mode.

Visualforce Page (StandardController) runs in User mode.
Visualforce Page (StandardController with extension) runs in System mode.
Visualforce Page (Custom Controller) - Based on the sharing keyword usage in the apex class.
Visualforce Component runs in depends on Visualforce page where it is used.

Macros runs in System mode.

Annonymous Apex runs in User mode.

Chatter in Apex runs in User mode.

Email Service runs in User mode.

All types of Jobs runs in System mode.

Apex Webservices (SOAP API and REST API) runs in System mode.

9. Send Email Actions in Salesforce

Send Email actions are supported in Lightning Experience only.

10. Test file naming convention for LWC

In your component bundle, create a folder called __tests__ and a JavaScript class called componentName.test.js. It’s a best practice to name the file after the component, followed by .test.js.

11. Canvas App

Canvas enables you to easily integrate a third-party application in Salesforce. Canvas is a set of tools and JavaScript APIs that you can use to expose an application as a canvas app. This means you can take your new or existing applications and make them available to your users as part of their Salesforce experience.

Canvas App Previewer

Canvas App Previewer is a development tool that lets you see what your canvas apps will look like before you publish them.

The third-party app that you want to expose as a canvas app can be written in any language. The only requirement is that the app has a secure URL (HTTPS).

apex:canvasApp is the tag to use in Visualforce page.

12. When Child Events get Created in Salesforce? 

While creating a new event/editing an existing event, we have the ability to invite people. So, for the invitees(users/contacts/leads), Salesforce internally creates separate events for each invitee with the flag isChild=TRUE.

13. Flow and Process Builder running mode

Flow in User Mode, PB in System Mode. Trigger the Flow from PB and it runs in System Mode. Mind. Blown.

14. What is ALM?

Application lifecycle management (ALM) is the product lifecycle management (governance, development, and maintenance) of computer programs. It encompasses requirements management, software architecture, computer programming, software testing, software maintenance, change management, continuous integration, project management, and release management.

15. What is the wire service?

Lightning web components(lwc) use reactive wire service to read Salesforce data.
It is Built on Lightning Data service.
Components use @wire in their JavaScript class to read data from one of the wire adapters in the lightning/ui*Api namespace.
Reactive wire service supports reactive variables, which are prefixed with $. If a reactive variable changes, the wire service provisions(requests) new data.

wire service syntax
import { adapterId } from 'adapterModule';
@wire(adapterId, adapterConfig)
propertyOrFunction;

16. How to Reset My Security Token when IP restriction is applied in the profile in Salesforce?

Use below URL
https://[SalesforceDomainHere].my.salesforce.com/_ui/system/security/ResetApiTokenEdit?retURL=%2Fui%2Fsetup%2FSetup%3Fsetupid%3DPersonalInfo&setupid=ResetApiToken

or

https://login.salesforce.com/_ui/system/security/ResetApiTokenEdit?retURL=%2Fui%2Fsetup%2FSetup%3Fsetupid%3DPersonalInfo&setupid=ResetApiToken

17. Will IsUnreadByOwner change fires trigger?

The IsUnreadByOwner field changing doesn't fire an update trigger.

Idea - https://success.salesforce.com/ideaView?id=08730000000BqU2

18. Sign in Error: 'Login Rate Exceeded'

When attempting log in you should limit the amount of requests to ensure proper processing.
The limit is 3600 calls per user per hour.
If this limit is exceed a “Login Rate Exceeded” error is generated in your application and Salesforce login history.
This limit ensures that our platform runs safely and efficiently.

19. Sender Policy Framework (SPF) and Salesforce SPF records

Sender Policy Framework is a simple email-validation system designed to detect email spoofing by providing a process to verify which providers are permitted to send emails on your behalf. It also aims to reduce the number of spam and fraud by making it harder for anyone to hide their identity.

If you’re sending an email from a Salesforce application and your domain is abc.com, you can create an SPF record that authorizes Salesforce.com mail servers as allowed mail servers for abc.com domain. When the recipient receives your email, it checks the SPF record of abc.com to determine if it’s a valid email. The message will have a high chance of delivery if it can be validated using SPF.

20. Advanced PDF to Render Visualforce Pages as PDF Files

Advanced PDF renders Visualforce pages as PDF files with broader support for modern HTML standards, such as CSS3, JavaScript, and HTML5. This change applies to both Lightning Experience and Salesforce Classic.

To use Advanced PDF, set renderAs="advanced_pdf" in the <apex:page> tag of a Visualforce page with API version 40.0 or later.

Limitations:

If you use inline CSS styles, set the API version to 28.0 or later. Also set <apex:page applyBodyTag="false">, and add static, valid <head> and <body> tags to your page, as in the previous example.
The maximum response size when creating a PDF file must be less than 15 MB before being rendered as a PDF file. This limit is the standard limit for all Visualforce requests.
The maximum file size for a generated PDF file is 60 MB.
The maximum total size of all images included in a generated PDF is 30 MB.
PDF rendering doesn’t support images encoded in the data: URI scheme format.
The following components don’t support double-byte fonts when rendered as PDF.
<apex:pageBlock>
<apex:sectionHeader>
These components aren’t recommended for use in pages rendered as PDF.
If an <apex:dataTable> or <apex:pageBlockTable> has no <apex:column> components that are rendered, rendering the page as PDF fails. To work around this issue, set the table component’s rendered attribute to false if none of its child <apex:column> components are rendered.

21. What does <article> HTML Tag do?

The <article> element identifies a self-contained piece of content which could theoretically be distributed to other websites and platforms as a stand-alone unit. The <article> element is a good choice to contain entire blog posts, news articles, and similar content.
Display: block
Usage: semantic or structural

22. Types of Flows

1. Auto Launched Flow
2. Screen Flow

Lightning Flow—the product that encompasses building, managing, and running flows and processes.
Flow Builder—a point-and-click tool for building flows.
Flow—an application that automates a business process by collecting data and doing something in your Salesforce org or an external system

23. Modify All

Users can read, edit, delete, transfer, and approve all records associated with this object, regardless of sharing settings.

24. Set Apex Class Access from Profiles

These settings apply only to Apex class methods. For example, apply the settings to Web service methods or any method used in a custom Visualforce controller or controller extension applied to a Visualforce page. Triggers always fire on trigger events (such as insert or update), regardless of profile settings.

25. What is meant by the Read / Unread status of leads?

A user will have a list of unread leads that they own and can be viewed under the list view of My Unread Leads.
When you transfer ownership of a lead, the lead will appear in the new owner's 'My Unread Leads' view, until they click on the lead.

Note: For leads owned by a Queue, the status will remain 'Unread', even if a member of the Queue reviews it.

26. What is the difference between (profile) login hours and (company information) business hours? Does business hours different from login hours or do business hours override the login hours?

Business hours don’t override profile hours. Login hours are for specifying when users can log in. Business hours are for specifying when the support team is available and to help manage other processes like escalations and milestones.

27. What information we get during PushTopic delete event?

Salesforce Id.
If the SOQL is SELECT Id, Name, Industry FROM Account, we will not get Name and Industry during delete event.

28. Delete Field History and Field Audit Trail Data

Use Apex or SOAP to delete field history and field history archive data.
To delete field history and audit trail data, the user permissions Delete From Field History and Delete From Field History Archive must be enabled through a permission set or a user profile. The org preferences to enable these permissions, Delete From Field History and Delete From Field History Archive, are located in Setup | User Interface.

Delete field history data, such as AccountHistory, and field history archive data by passing in a list of ID values as strings using the Apex or SOAP delete() method. The Apex delete() method also works with a list of sObjects with the Id field populated.

The sObject acts like a template. All rows that match the sObject’s fields and values are deleted. You can only specify fields that are part of the big object’s index. You must specify all fields in the index. You can’t include a partially specified index or non-indexed field, and wildcards are not supported.

Sample for deleting AccountHistory:

List<AccountHistory> ah = new List<sObject>();    
ah.addAll( [ SELECT Id FROM AccountHistory WHERE AccountId = '001d000000Ky3xIAB' AND CreatedDate = YESTERDAY ] );    

Database.delete(ah);    

Samples for deleting from FieldHistoryArchive:

List<FieldHistoryArchive> fha = new List<sObject>();  
fha.addAll([SELECT FieldHistoryType, ParentId, CreatedDate, HistoryId FROM FieldHistoryArchive WHERE FieldHistoryType = 'Account' AND  ParentId = '001d000000Ky3xIAB' AND CreatedDate = '2017-11-28T19:13:36.000z' AND  HistoryId = '017D000000ESURXIA5']);  

Database.delete(fha); 

29. lightning-record-view-form component

A lightning-record-view-form component is a wrapper component that accepts a record ID and is used to display one or more fields and labels associated with that record using lightning-output-field.

lightning-record-view-form requires a record ID to display the fields on the record. It doesn't require additional Apex controllers or Lightning Data Service to display record data. This component also takes care of field-level security and sharing for you, so users see only the data they have access to.

Supported Objects
This component doesn't support all Salesforce standard objects. For example, the Event and Task objects are not supported.

30. Example for Ternary operator:

Integer ListPrice = 50;
Integer SalesPrice = 100;
Integer TotalAmount = ListPrice > 50 ? ListPrice : SalesPrice;
System.debug(‘::TotalAmount::’+ TotalAmount);

April 19, 2019

Time dependent process actions in Process Builder

In Process Builder time based actions are available when "only when a record is created" is selected. For "when a record is created or edited", if you select "Do you want to execute the actions only when specified changes are made to the record?" in the criteria then time based actions will appear.


April 18, 2019

OnLoad in Salesforce Lightning Web Component

Component HTML:


  1. <template>  
  2.     {TestParams}  
  3. </template>  

Component JAVASCRIPT:


  1. import { LightningElement, track } from 'lwc';  
  2.   
  3. export default class SampleLWC extends LightningElement {  
  4.   
  5.     @track TestParams;  
  6.   
  7.     connectedCallback() {  
  8.   
  9.         this.TestParams = 'Testing'  
  10.   
  11.     }  
  12.   
  13. }  

Output:


April 17, 2019

How to create Lightning Web Component in Salesforce?

Lightning Web Components development requires Visual Studio Code. Check the below link if you want to set it up.

http://www.infallibletechie.com/2018/09/how-to-install-and-set-up-vs-code-for.html

1. Make sure Lightning Web Components extension is installed and enabled.


2. Use SFDX: Create Lightning Web Component command.


3. Select force-app\main\default\lwc.


4. Enter a desired name for the component.


April 14, 2019

Test Lightning Web Components

Jest is a powerful tool with rich features for writing JavaScript tests. Use Jest to write unit tests for all of your Lightning web components. To run Jest tests, install lwc-jest, which sets up all the necessary Jest configurations for a Salesforce DX project.

Run Jest tests at the command line or (with some configuration) within your IDE. Jest tests don’t run in a browser or connect to an org, so they run fast. When run in “watch mode” they give you immediate feedback while you’re coding. Jest tests work only with Lightning web components, they don’t work with Aura components.

1. Download and install node.js and npm.

Node.js - https://nodejs.org/en/
npm - https://nodejs.org/en/

2. Open a Salesforce project in VS Code which has LWC component.

3. Go to Terminal tab.

4. Execute npm init command.


5. Execute npm install command.


6. Execute npm install @salesforce/lwc-jest --save-dev command. This will take sometime to complete.

7. Next, to identify your test script, add an entry in the scripts block of your project’s package.json file. The line must include a name and a command. You can choose the name. The command must be lwc-jest and can optionally include a supported flag like --watch or --debug.


8. Create __tests__ folder in the component folder.



9. To ensure that the __tests__ folder and its contents are never saved to Salesforce, add this glob pattern to the .forceignore file for each of your projects.

**/__tests__/**


10. Create new js test file.


11. Use componentName.test.js naming convention.

12. Use npm run test:unit to run the test.


Sample Code:

Component:


  1. <template>  
  2.     <lightning-card title="Hello" icon-name="custom:custom14">  
  3.         <div class="slds-m-around_medium">  
  4.             Hello, {greeting}!  
  5.         </div>  
  6.     </lightning-card>  
  7. </template>  

JAVASCRIPT Controller:


  1. import { LightningElement } from 'lwc';  
  2.   
  3. export default class Hello extends LightningElement {  
  4.   
  5.     greeting = 'World';  
  6.   
  7. }  


Test class JAVASCRIPT Controller:
  1. import { createElement } from 'lwc';  
  2. import Hello from 'c/hello';  
  3.   
  4. describe('c-hello', () => {  
  5.     afterEach(() => {  
  6.         // The jsdom instance is shared across test cases in a single file so reset the DOM  
  7.         while (document.body.firstChild) {  
  8.             document.body.removeChild(document.body.firstChild);  
  9.         }  
  10.     });  
  11.   
  12.     it('displays greeting', () => {  
  13.         // Create element  
  14.         const element = createElement('c-hello', {  
  15.             is: Hello  
  16.         });  
  17.         document.body.appendChild(element);  
  18.   
  19.         // Verify displayed greeting  
  20.         const div = element.shadowRoot.querySelector('div');  
  21.         expect(div.textContent).toBe('Hello, World!');  
  22.     });  
  23. });  

Imports
First, the test imports the createElement method. This method is available only in tests. The code must also import the component to test, which in this case is c/hello. Use these imports later to create the component under test.
import { createElement } from 'lwc';
import Hello from 'c/hello';

describe block
A describe block defines a test suite. A test suite contains one or more tests that belong together from a functional point of view.
describe('c-hello', () => {
    ...
});
We recommend having a top level describe block with a description matching the component name. Add more describe blocks that group functionality only if necessary.

For hello.test.js, a single describe is sufficient. For more complex components, it may make sense to have several describe blocks that group things into categories like error scenarios, empty input, wired data, regular data, and so on.

Cleanup
The Jest afterEach() method resets the DOM at the end of the test.
Since a browser isn’t running when tests run, Jest uses jsdom to provide an environment that behaves much like a browser’s DOM or document. Jest has a dependency on jsdom, which is a Node.js project, so jsdom is downloaded during installation of the lwc-jest project the same way Jest itself is.
Each test file shares a single instance of jsdom, and changes aren’t reset between tests inside the file. Therefore it’s a best practice to clean up between tests, so that a test’s output doesn’t affect any other test.
afterEach(() => {
    // The jsdom instance is shared across test cases in a single file so reset the DOM
    while (document.body.firstChild) {
        document.body.removeChild(document.body.firstChild);
    }
});
Jest also has other methods that you can use to perform setup and cleanup tasks. See jestjs.io/docs/en/setup-teardown.

it (or test) block
Note
NOTE it is an alias for test. Use whichever word allows you to describe the expected behavior accurately.
An it block describes a single test. A test represents a single functional unit that you want to test. Write the it to describe the expected behavior of that function. For example, the hello component displays “Hello, World!”, so the it block tests that the hello component displays a greeting.
it('displays greeting', () => {
    ...
});

Create the component under test
The test uses the imported createElement method to create an instance of the component to test, in this case, c-hello.
const element = createElement('c-hello', {
    is: Hello
});

Add the component to the DOM
The test then calls appendChild to add the component to the test’s version of document.
The document.body.appendChild() call attaches the Lightning web component to the DOM and renders it. Which also means that renderedCallback() lifecycle method gets called.
document.body.appendChild(element);
The next step is to use a standard DOM query method to search the DOM for the element. Use element.shadowRoot as the parent for the query. It's a test-only API that lets you peak across the shadow boundary to inspect a component’s shadow tree. It’s the test equivalent of this.template.
const div = element.shadowRoot.querySelector('div');

Asserts
Finally, the expect statement is an assertion of the success condition: that the text of the element is “Hello, World!”
const div = element.shadowRoot.querySelector('div');
expect(div.textContent).toBe('Hello, World!');
Jest supports lots of matchers like toBe and toMatchObject that make it easy to check that a value meets a condition.