Are you a Salesforce developer that has been tasked with building a complex app involving multiple Lightning Web Components (LWC’s)?
The most important thing to understand is all the ways these components can communicate. Without a solid understanding of this concept, you may struggle and inadvertently create a poor performing or error prone app.
That is why I am happy to announce that my latest Pluralsight course, “Communicate Between Salesforce Lightning Web Components” has just been released. This is not a course for beginners new to LWC’s or Salesforce. But, if you plan on building an app that involves multiple LWC’s and you already know the basics, then this course is for you.
Communicate Between Salesforce Lightning web Components
In this course you will learn how to effectively communicate between LWC’s. First you will discover the three methods used to communicate between components. Then you will learn details about each method by seeing how they work in a real-world app. By the end of the course, you will know how to build your own high-performing Lightning-based app that is assembled with Lightning Web Components. This course is focused solely on LWC communication.
I hope you find the course useful. If you do check it out and have feedback, I would love to hear it – good or bad. You can give feedback through Pluralsight or here on my blog. Either way, it would be appreciated. Thank you.
I am very proud to announce the release of my latest Pluralsight course, “Customizing Salesforce with Lightning Aura Components“. This is actually a total re-write of my most popular course, “Customizing Salesforce with Lightning Components”, released in 2017. The key word change in the title is the addition of the word, “Aura“.
New Pluralsight Course, which includes working with VS Code and the CLI
This course is different because at the time that course was released, Lightning Components were not called Lightning Aura Components AND most importantly, the new modern toolset known as Salesforce DX was not yet available. There were also no Lightning Web Components available yet.
I personally believe that for many developers, transitioning to LWC would be much easier if they were to first learn to build simple Aura components using the new modern tools first.
In this course, all those great shiny new tools will be used to build very simple Aura Lightning Components. The original course used the online Developer Console, which is what Trailhead still uses in all their content about Aura Components. On Trailhead, the new tools are only used for Lightning Web Components.
So, if you want to learn about building Aura Components, while also embracing the new modern toolset, this course is perfect for you. And if you want to learn about Lightning Web Components (LWC’s), then you can check out the “Building Your First Lightning Web Component (LWC) for Salesforce” course that I released earlier this year.
Either way, you will be knowledgeable in all the latest that Salesforce has to offer. I personally believe that for some developers, transitioning to LWC would be much easier if they were to first learn to build simple Aura components using the new modern tools first.
This course includes a GitHub Repo that features all the code covered in the course. The material covered includes the following:
Understanding the Lightning Component Framework
Refer to the following blog post #1 . In this post/Pluralsight module), you will learn:
This will be the last of a series of posts I will be doing over the next few weeks. This particular post will cover working with the new Salesforce Mobile App. The series will all lead up to the introduction of my new course titled, “Customizing Salesforce with Lightning Aura Components” from Pluralsight. This course is a total re-write of my most popular course, “Customizing Salesforce with Lightning Components: Getting Started“, which was released back in early 2017. It will focus on using the new modern toolset that Salesforce offers as part of Salesforce DX.
Image comparison of Salesforce1 (left) vs New Salesforce Mobile App (right)
Right away you should have noticed that the details view includes more fields and this is primarily because of the denser view with labels to the left and less space between fields. This was a feature introduced for Lightning Experience to improve usability.
There are other big features like:
Favoriting and Search icon links in the top menu bar
There is also a really cool download icon that allows authorized users to send links to other authorized users.
And the menu navigation has changed quite a bit and now mirrors what is found in Lightning Experience
Intuitive Navigation for Salesforce Mobile that mirrors Lightning Experience
There are also some Lightning App Builder improvements that let you preview pages better and use filters to set component visibility.
Set Component Visibility in Lightning App Builder
Using the Salesforce Mobile App QuickStart Page
There will be some steps Salesforce Administrators/Developers will need to take to support the transition to the new Salesforce Mobile App. To assist with that process, Salesforce has provided a new link in Setup called, New Salesforce Mobile App Quickstart.
The QuickStart includes a section called “Enable Your Customizations for Mobile” and in it is the following:
Run the Salesforce Optimizer for Mobile Lightning Pages Report (Beta) – Mostly includes recommendations for how you can fine-tune pages/apps for mobile. Once generated, a copy will be available in Files.
Update Your Lightning Apps for Mobile – Adds the phone form factor to apps. You can also do this manually through App Manager.
Update Your Pages for Mobile – Adds the phone form factor to desktop-assigned pages. You can also do this manually though Lightning App Builder.
Wrapping up the Course
The key points I hope you take away from the course are:
Don’t be afraid to embrace Aura components, even if you are a junior developer, a Salesforce Admin or a developer that has only worked with Visualforce. Simple Aura components are not difficult and can really improve the Lightning Experience for your customers.
Embrace the new modern tools that Salesforce offers and which this course goes over in depth. Even though you can create Aura components just using Developer Console, I strongly recommend that you embrace the modern toolset and Visual Studio Code. This will also help you to transition to creating Lightning Web Components, which can only be created with these tools.
When using Apex, always consider security since CRUD and FLS security is not automatically enforced.
However, if you can utilize the Base Lightning Components that do not use Apex, consider using them. It means you will not have to write Apex or Apex Unit tests, or worry about security.
Always consider the Usability of your components by using the Design Resources and making the components as flexible as possible.
Keep learning and pass what you learn onto others in the Salesforce community.
All of the code shown in the course, can be accessed through the following GitHub repo.
And if you are interested in going deeper with Aura components, check out my other intermediate Pluralsight course about Lightning Component Best Practices.
The course should be released soon. Tune in here for an announcement.
This will be the fourth of a series of posts I will be doing over the next few weeks. This particular post will cover working with the Record Form Base Lightning Component. The series will all lead up to the introduction of my new course titled, “Customizing Salesforce with Lightning Aura Components” from Pluralsight. This course is a total re-write of my most popular course, “Customizing Salesforce with Lightning Components: Getting Started“, which was released back in early 2017. It will focus on using the new modern toolset that Salesforce offers as part of Salesforce DX.
Working with Record Forms
The recordEditForm and recordViewForm components have been around for a while, but the recordForm component was introduced in Summer 18 and was a big improvement. In fact, I was so impressed with this component, I wrote about it on this blog.
The recordForm component represents the best of two other components and essentially merges them into one. This means you will need to write less JavaScript code in the form of handlers, such as onload and onsubmit because the new component will handle these automatically.
Along with less markup, since you will not have to use lightning:input or lightning:output, along with cancel and submit buttons. They are provided for you automatically. And finally, the recordForm component is exposable to more platforms, which at this time includes Lightning Experience, Lightning Communities, Salesforce Mobile App, along with Lightning Out combined with Visualforce.
And the Drawbacks? Well, it is slightly less flexible and as of now, there is a known issue involving validation that I hope you consider voting for (since that is the only way Salesforce will fix it).
Creating a New Quick Case Component
In this section, I will show you how to build a component that let’s users quickly create a new case. The end result will be a component like this:
Quick Case Create Component
This component will use the recordForm base lightning component. Here is the code for the markup:
And here is the code for the client-side controller. Note that it includes a commented method that would handle validation, since the component unfortunately does not do this (at this time – refer to issue above). I don’t really consider this a workaround, since the whole purpose of the component was to eliminate the need for the additional code. I personally think Salesforce needs to fix it, and hope you agree.
({
handleSuccess : function(cmp, event, helper) {
cmp.find('notifLib').showToast({
"variant": "success",
"title": "Case Created",
"message": "Record ID: " + event.getParam("id")
});
}
// },
// handleValidation : function(cmp, event, helper) {
// // NOTE: This method will handle validation if you specify which field to check for specifically, which is
// // not a good workaround since the component should handle this for you without the need to write
// // all this unecessary code (especially since the whole point of the component is to lessen the
// // amount of code that needs to be written). That is why it was not mentioned in the actual course.
// var evtFields = event.getParam("fields");
// var reqField = 'Origin';
// if (evtFields.hasOwnProperty(reqField)) {
// event.preventDefault(); //Stops the record from being created
// cmp.find('notifLib').showToast({
// "variant": "error",
// "header": "Error was encountered",
// "message": "The following field is required: " + reqField
// });
// }
})
The code includes the notifications base lightning component. This is used to alert the user with a toast message when the case was added successfully.
Creating Quick Actions
In addition to including this component on the Sales Home page, I exposed it as a quick action and then created a global action using the following steps in Setup.
In Quick Find, type “global” and select Global Actions.
Click New Action.
Select “Lightning Component” as the Action Type.
Select the quickCase component from the drop down list.
Enter a label as “Quick Case Create” and tab to next line.
Click Save to Finish.
After creating the global action, you still need to add the new action to the Publishers layout, which you do using the following steps:
In Quick Find, type “Publisher” and select Publisher Layout.
Click Edit to modify the default layout.
Select “Mobile and Quick Actions”.
Scroll down to the section for Salesforce Mobile and click the override the predefined actions link.
Drag the Quick Case Create action onto the section.
Click Save to finish.
In the next and final post, I will go over the newly redesigned Salesforce Mobile App.
This will be the third of a series of posts I will be doing over the next few weeks. This particular post will cover working with Salesforce Data. The series will all lead up to the introduction of my new course titled, “Customizing Salesforce with Lightning Aura Components” from Pluralsight. This course is a total re-write of my most popular course, “Customizing Salesforce with Lightning Components: Getting Started“, which was released back in 2017. It will focus on using the new modern toolset that Salesforce offers as part of Salesforce DX.
Working with Controllers
In the last post, I walked you through creating the updateCellNumber Aura component in Visual Studio Code. I also stepped you through how to add a design file so that the placeholder value was easily modifiable in Lightning App Builder.
So far this component will only show a windows alert when the submit button is pressed. I am going to show you how to change that and have it update the Salesforce database instead.
Lightning Components have two ways of dealing with Salesforce data:
In this post, I will only covering the second method of using Apex to write server-side code.
Working with Apex and DML
Apex is strongly-typed object-oriented proprietary language developed by Salesforce. Since Salesforce is a multi-tenanted environment, Apex is subject to limits.
DML or Data Manipulation Language is what Salesforce uses to insert, update or delete a Salesforce record. To change the updateCellNumber component so that it writes to the Salesforce database, I will need to add a Class that uses both Apex and DML. The class will be named updateCellNumberApex (so that it is not named the same as the client-side JavaScript controller). Any server-side methods used by Lightning components must have the @AuraEnabled annotation. They also must be public and static. The code for the class will be as follows:
public with sharing class updateCellNumberApex {
@AuraEnabled()
public static void CellNumberUpdate(String cellNumber) {
List<User> users = [SELECT MobilePhone FROM User where
Id =: UserInfo.getUserId()];
if ( users.size() > 0 ) {
users[0].MobilePhone = cellNumber;
update users;
}
}
}
Once the class has been added, I will need to modify the component markup for updateCellNumber so that it is linked to this class. I do that by adding the following attribute to the aura:component tag, like this:
I will then need to switch to the client-side JavaScript controller and start by removing the code that produced a windows alert and replace it with the following:
var cellNumber = cmp.find("phone").get("v.value");
var action = cmp.get("c.CellNumberUpdate");
action.setParams({ "cellNumber" : cellNumber });
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
alert(state);
}
});
$A.enqueueAction(action);
Creating a New Open Cases Component
This component will display a list of open cases and will be named openCases. The final component will look like the following:
Open Cases Configureable Component
This Aura component will utilize the lightning:datatable base lightning component. Here is the code for the component markup:
The first part of this code is used to define the columns that will be used in the datatable. Notice that the first one is of the type url and that it has an additional definition for the typeAttributes. This is because this column will not only display the case subject, but will include a link to the case detail record.
The callback function will get whatever records are returned and then loop through those records and set the linkName so that it references the Cases record Id.
This component will utilize an Apex controller named getOpenCasesApex. It includes code needed to check for the appropriate FLS and CRUD level security. It also includes cacheable=true for the @AuraEnabled annotation in order to take advantage of caching for performance.
public with sharing class getOpenCasesApex {
@AuraEnabled(cacheable=true)
public static List<Case> getOpenCases(Integer numRecords) {
// Code needed to check for proper access
String [] caseFields = new String[] {'Id','Type','Reason','Subject','Status'};
Map<String,Schema.SObjectField> caseMap = Schema.SObjectType.Case.fields.getMap();
for (String fieldToCheck : caseFields) {
if( !caseMap.get(fieldToCheck).getDescribe().isAccessible()) {
throw new System.NoAccessException();
}
}
List<Case> caseList = [SELECT Id,Type,Reason,Subject,Status FROM Case
WHERE IsClosed = false
LIMIT : numRecords];
return caseList;
}
}
And finally, it includes a numRecords input parameter, which is passed in form the value set when the component is configured in Lightning App Builder. The associated design file for this component is as follows:
<design:component label="Configurable Open Cases Component">
<design:Attribute name="numRecords" label="Number of Records Returned" placeholder="10" />
</design:component>
In the next post, I will go over how to design components that do not require an Apex controller.
This will be the second of a series of posts I will be doing over the next few weeks. They will all lead up to the introduction of my new course titled, “Customizing Salesforce with Lightning Aura Components” from Pluralsight. This course is a total re-write of my most popular course, “Customizing Salesforce with Lightning Components: Getting Started“, which was released back in 2017. It will focus on using the new modern toolset that Salesforce offers as part of Salesforce DX.
Using an Interactive Development Environment (IDE)
For most modern web developers, their Interactive Development Environment (IDE) is a key to their success. For Salesforce developers, the best choice for an IDE is the Salesforce Extensions for Visual Studio Code.
If you have been a Salesforce developer for a while, then this may be new to you. You may be familiar with the Force.com IDE or Interactive Development Environment for Eclipse, which is incidentally not being supported by Salesforce any more.
Salesforce Extension Pack for VS Code
Getting Setup with an IDE
To use the IDE, you will first need to install the latest version of Visual Studio Code. After this has been installed, you can open it up and click the extensions icon on the left toolbar.
Install Salesforce Extension Pack by clicking Extensions Icon
You will also need to install the Salesforce Command Line Interface (CLI). This powerful command line interface allows you to do several things with your Salesforce org, such as:
Build and load source code (such as Aura components, Apex classes, Lightning Web Components and).
Export data from any Salesforce org and import it into your scratch org, which is a temporary org that has no data loaded by default.
Execute both Apex server-side and client-side JavaScript tests.
Once you get used to working with the Salesforce Extensions, you might want to check out the GitHub repo, since it is open source. You can get a lot of information about the extensions on the ReadMe page, as well and browse the useful Wiki and Issues tabs.
Understanding Salesforce DX (SFDX)
Salesforce DX represents a whole new set of developer tools. They represent a source-driven development model, which is considered more modern. It is all built around the CLI, which you just learned about. Most importantly it represents a new way of Salesforce development now known as “Packaging Development”.
Prior to packaging development, the only way developers had to deploy their code was to package it up in a Sandbox org and then deploy it to production. This made the salesforce org the “source of truth”, as developers like to call it. But the new model moves the source of truth from the org to a version control system, like Git.
Before you can create any Aura components in VS Code, you will need to do the following things first:
Authorize a DevHub org using either the command palette or the sfdx force:auth:web:login CLI command.
Create a Salesforce project using either the command palette or the sfdx force:project:create CLI command.
Create a scratch org using either the command palette or the sfdx force:org:create CLI command.
Creating an Aura Component in Visual Studio (VS) Code
After you have authorized your DevHub and created a project, you can create an Aura component, by browsing to the Aura folder, right-clicking and selecting “SFDX: Create Lightning Component”.
Creating Aura Component in VS Code
Here is the markup code for a very basic component that can be used to update a users mobile phone number.
And here is the JavaScript for the controller , in which the component will begin by only being able to create a windows alter that displays the number entered when the user clicks Submit.
The main thing you will need in order to expose your new component to Lightning App Builder is the following attributes on the required aura:component tag:
But in order to make the component more usable to Admins that might build Lightning Pages using these components, it is a good idea to always include a design resource, such as this:
You can then save all your changes and push them to the scratch org using either the command palette or the sfdx force:source:push CLI command. You will also need to open the scratch org using either the command palette or the sfdx force:org:open CLI command.
One the org is open, to add the new component to the Sales home page, use App Launcher to go to the Sales app and then click the gear icon and select Edit Page.
Edit Page is used to access Lightning App Builder
You can then just scroll down the list of components until you get to the custom ones and drag the Update Cell Number one onto the design surface.
To finish you just need to save and activate the changes. You can then use the Back button to go back to the Sales home page and see the final component.
Update Cell Number Component, so far
In the next post, this component will be improved on and tied to the Salesforce database.
This will be the first of a series of posts I will be doing over the next few weeks. They will all lead up to the introduction of my new course titled, “Customizing Salesforce with Lightning Aura Components” from Pluralsight. This course is a total re-write of my most popular course (so far), “Customizing Salesforce with Lightning Components: Getting Started“, which was released back in 2017. It will focus on using the new modern toolset that Salesforce offers as part of Salesforce DX.
Understanding the Lightning Component Framework
Lightning components (now called Aura components) were introduced in 2014. At that time, the web standards that existed offered only a limited amount of what developers needed and that is why Salesforce built them on top of the Aura Framework. It was basically, to compensate for what the standards lacked.
Flash forward to 2019 and a LOT has changed in the web development world. That is why in 2019, Salesforce announced the release of Lightning Web Components (LWC’s). It was also at that time that the original Lightning Components were renamed to Aura Components. They co-exist and are completely interoperable with LWC’s.
Who Should be Building Aura Components?
It probably will not surprise you to know that Salesforce developers are perfect for this, but what you might not realize is that so are junior Salesforce developers.
Senior or Junior Salesforce Developers
Another group you may not think of is Salesforce Administrators. You see, Aura components are way simpler to create then Lightning Web Components. Yes, they do still require the developer to know a little about HTML and JavaScript, but since the introduction of Lightning components back in 2014, they have gotten a lot simpler to work with. So, as long as the Admin is seasoned and may even consider themselves as a Super Admin, then I think they too can embrace creating Aura components.
Salesforce Super Admins
Where Can Aura Components Be Used?
Lightning pages
This includes App pages, Home and Record Pages, and even a new Embedded Service Page. The embedded service page will not be covered in this course, but the app and home pages will.
Wizard from Lightning App Builder
salesforce mobile app
In late 2019, Salesforce launched a new and completely redesigned Salesforce Mobile App. You can learn more about it by visiting the New Salesforce Mobile App Quickstart in Setup. This will be covered in the final module on “Creating Components for Salesforce Mobile”.
Access the New Salesforce Mobile App QuickStart from Setup
Other places
These other areas are beyond the scope of this course, but just so you are aware, there is also:
Quick Actions
Stand-alone apps
Inside Visualforce pages
On other platforms such as Heroku, using Lightning Out
Anatomy of an Aura Component Bundle
An Aura component can be made up of several physical files that reside in what is known as a component bundle. Even though there are 8 files that can make up a component bundle, most simple components will only need to access a couple:
Component or Markup file – Uses a .cmp file extension and is a required file and there can only be one per bundle. All markup must be encased in an <aura:component> tag and can include references to other components.
Controller or JavaScript file – Uses a .js file extension and will contain all the client-side methods needed to handle events in your component.
Creating an Aura Component Bundle
The easiest way to create an Aura component is using the online Developer Console. This will be covered only once in this first module. The rest of the course will cover creating bundles using the new modern toolsets.
You can access the Developer Console by logging into a Developer org, click the gear icon and select Developer Console.
Access the online Developer Console
This will launch a new window and from here, you can go to File -> New -> Lightning Component.
Create a new Lightning Component in Developer Console
The initial component I will show viewers how to build is very simple and will be used by Salespeople to update their cell number. From the New Lightning Bundle dialog, you only need to enter the name “updateCellNumber” and select the Lightning Tab and Lightning Page checkboxes in Component Configuration. And finally click Submit.
Create new Lightning Bundle in Developer Console
The component markup will be very simple to begin with and will include 3 Lightning Base Components. as the course progresses, this component, along with others will be expanded upon.
I am VERY happy to announce that I am very close to releasing a new Pluralsight course called “Customizing Salesforce with Lightning Aura Components”. Well, kind of a new course.
Upcoming New Pluralsight Course
It is a total re-write of my most popular course (so far), “Customizing Salesforce with Lightning Components: Getting Started“, which was released back in 2017. That was right before Salesforce DX was released and all the other modern developer tools that Salesforce now promotes (for very good reasons).
In this course, all those great shiny new tools will be used to build very simple Aura Lightning Components, as they are now called. The original course used the online Developer Console, which is what Trailhead uses in all their content about Aura Components. On Trailhead, the new tools are only used for Lightning Web Components.
So, if you want to learn about building Aura Components, while also embracing the new modern toolset, this course is perfect for you. And if you want to learn about Lightning Web Components (LWC’s), then you can check out the “Building Your First Lightning Web Component (LWC) for Salesforce” course that I released earlier this year.
Starting next week, I will be releasing a series of weekly blog posts that will feature what content will be covered in each Pluralsight module, followed by an announcement of the courses release.
In that course, Chuck walked everyone through the Open Source Recipes Repo that Salesforce provided when it first released LWC’s. I remember in one part of that excellent course, that Chuck mentioned that we could not see the source code for any of the base Lightning components. Specifically, he mentioned the lightning:card component. In the course he said,
“And if I were able to look at the source code for that component, I’m sure that I would see that their attribute title is a type Aura Component Array…”
Well, the GREAT news is that Salesforce has released all those Base Lightning Components as open source on GitHub. So now everyone can see that code and learn about the best practices that Salesforce has implemented in those components.
Anyone can clone or download the source code and then follow the directions in the README to spin up these components in a scratch org. Once you do, you can open that scratch org and using the App Launcher, browse to the Base Components app. From here, they can select one of the tabs, such as the one for the Layout Components, and see first-hand how that lightning Card component works, as well as click the link to view the source.
Is that not the coolest thing in the world? I sure think so.
I would be remiss if I did not also mention the Pluralsight course I just released called, “Building Your First Lightning Web Component for Salesforce“. It is not free, but come on, Pluralsight is soooooo worth the subscription cost.
This will be the sixth of a series of posts I will be doing over the next few weeks. They will all lead up to the introduction of my new course in January 2020 titled, “Building Your First Lightning Web Component for Salesforce” from Pluralsight. These posts will contain final code snippets of the code used in each course module, but will not include all the tips and best practices about using Visual Studio Code and SFDX, along with the way I personally approach teaching in my video courses.
Handling Testing and Wrapping Up
If you are already a Salesforce developer then you know that server-side Apex Unit tests are required, but client-side JavaScript tests are not and if you are like most developers, you probably think that creating tests should be optional, kind of like documenting, right?
You might not believe this, but writing tests (even for non-required JavaScript) can actually save you a lot of time, such as:
Time from chasing down bugs
Fixing those bugs
Releasing your fix using whatever release process your company uses
Introducing Jest
Jest is an easy to use tool that was originally created by the engineers at Facebook. It is now supported as open-source by the community. Salesforce DX provides a utility that lets you setup and configure Jest for your LWC project.
There are a few steps involved in getting this setup, which include:
Install prerequisites (which includes the latest versions of node.js and npm). Even if you already have node installed, it is recommended that you install the Long Term Support Version of Node.js, which will also include npm. This will guarantee that critical bugs will be fixed for a total of 30 months. You can install the LTS version from here.
Setup LWC VS Code project with npm – Go to the Terminal window in your VS Code project and from the root folder, run the following command:
npm init
This will create a package.json file. Just hit enter through all the prompts
Install sfdx-lwc-jest and dependencies – Also from Terminal window:
npm install
This will create a package-lock.json file
npm install @salesforce/sfdx-lwc-jest --save-dev
Identify test script – Open the package.json file and add this to the scripts section:
Unlike Apex unit tests, Jest tests are run locally and are completely independent of Salesforce. As a best practice, you should create all your tests in a special folder at the root of your project that is named __tests__. If you look at the .forceignore file in your project, you will see that an entry for this folder already exists, thus excluding any tests from being pushed to your scratch org.
In the course, I walk you through creating a test of the leadList component. That test is just a JavaScript file that is created in the __tests__folder and is named: leadList.test.js (which is also a recommended best practice). In that folder, there is also a data subfolder that contains two JSON files named: getLeads.json and getNoLeads.json. Below is the code for the test:
import { createElement } from 'lwc';
import leadList from 'c/leadList';
import { registerApexTestWireAdapter } from '@salesforce/sfdx-lwc-jest';
import searchLeads from '@salesforce/apex/LeadSearchController.searchLeads';
// Represent a list of valid records
const mockGetLeads = require('./data/getLeads.json');
// Represent a list of no records
const mockGetNoLeads = require('./data/getNoLeads.json');
// Register the Apex wire adapter
const searchLeadsAdapter = registerApexTestWireAdapter(searchLeads);
describe('c-lead-list', () => {
beforeAll(() => {
// Use fake timers as setTimeout
jest.useFakeTimers();
});
// Best practice to cleanup after each 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);
}
});
describe('searchLeads @wire returns records with search parameter', () => {
it('called with data from input', () => {
const USER_INPUT = 'Bertha';
const SEARCH_TERM = { searchTerm: USER_INPUT };
// Create the leadList element
const element = createElement('c-lead-list', {
is: leadList
});
document.body.appendChild(element);
// Simulate user input
const inputValue = element.shadowRoot.querySelector('lightning-input');
inputValue.value = USER_INPUT;
inputValue.dispatchEvent(new CustomEvent('change'));
// Run the fake timers
jest.runAllTimers();
// Return a promise to wait for asynchronous results
// and fail if promise is rejected
return Promise.resolve().then(() => {
expect(searchLeadsAdapter.getLastConfig()).toEqual(
SEARCH_TERM
);
});
});
it('renders data of one record', () => {
const USER_INPUT = 'Bertha Boxer';
// Create the leadList element
const element = createElement('c-lead-list', {
is: leadList
});
document.body.appendChild(element);
// Simulate user input
const inputValue = element.shadowRoot.querySelector('lightning-input');
inputValue.value = USER_INPUT;
inputValue.dispatchEvent(new CustomEvent('change'));
// Run the fake timers
jest.runAllTimers();
// Use the searchLeadsAdapter to emit data
searchLeadsAdapter.emit(mockGetLeads);
// Return a promise to wait for asynchronous results
// and fail if promise is rejected
return Promise.resolve().then(() => {
// select some elements that would be rendered if it succeeded
const detailElement = element.shadowRoot.querySelector('lightning-datatable');
const rows = detailElement.data;
expect(detailElement.length).toBe(searchLeadsAdapter.length);
expect(rows[0].Name).toBe(mockGetLeads[0].Name);
});
});
it('renders data when no record is available', () => {
const USER_INPUT = '';
// Create the leadList element
const element = createElement('c-lead-list', {
is: leadList
});
document.body.appendChild(element);
// Simulate user input
const inputValue = element.shadowRoot.querySelector('lightning-input');
inputValue.value = USER_INPUT;
inputValue.dispatchEvent(new CustomEvent('change'));
// Run the fake timers
jest.runAllTimers();
// Use the searchLeadsAdapter to emit data
searchLeadsAdapter.emit(mockGetNoLeads);
// Return a promise to wait for asynchronous results
// and fail if promise is rejected
return Promise.resolve().then(() => {
// select some elements that would be rendered if it succeeded
const detailElement = element.shadowRoot.querySelector('lightning-datatable');
expect(detailElement.length).toBe(searchLeadsAdapter.length);
});
});
});
describe('searchLeads @wire returns error', () => {
it('shows error panel', () => {
// Create the leadList element
const element = createElement('c-lead-list', {
is: leadList
});
document.body.appendChild(element);
// Emit error from @wire
searchLeadsAdapter.error();
// Return a promise to wait for any asynchronous DOM updates. Jest
// will automatically wait for the Promise chain to complete before
// ending the test and fail the test if the promise rejects.
return Promise.resolve().then(() => {
const errorPanelEl = element.shadowRoot.querySelector(
'c-error-panel'
);
expect(errorPanelEl).not.toBeNull();
});
});
});
})
To run the test seen above, you will need to return to the Terminal window and run this command:
npm run test:unit
Wrapping Up
So, this is the last post in the series and I should be announcing the release of this course soon. Sorry it has taken so long, but I hope you go away with these thoughts: