SlideShare a Scribd company logo
1 of 49
Lightning Web Components Developer
Workshop
Forward-Looking Statements
Statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and
assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the
results expressed or implied by the forward looking statements we make. All statements other than statements of historical fact could be deemed forward-looking,
including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or
plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and
customer contracts or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new
products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in
our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the
immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new
releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise
customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the
most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures
are available on the SEC Filings section of the Investor Information section of our Website.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be
delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available.
Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
Agenda and Training Overview
Time Section Focus
09:30 - 11:00 Component Communication Parent-Child, Child-Parent, LWC-LWC, Aura-LWC
11:00 Break Coffee Break
11:15 - 11:45 Lightning Locker Best Practices
11:45 - 12:30 Unit Testing Testing with JEST
12:30- 01:30 Lunch
01:30 - 03:00 Exercise 3 Build a bear tracking app
03:00- 03:15 Break Coffee Break
03:15 - 04:00 Exercise 3 (contd) Build a bear tracking app
04:00 - 04:30 Lightning Web Components Open Source (if time permits)
Intercomponent Communication
Intercomponent Communication
• Parent to Child
• Child to Parent
• Lightning web component to Lightning web component
• Lightning web component to Aura component
Parent to Child Communication
Child
@api itemName;
Parent HTML
Parent <c-todo-item item-name={name}></c-todo-item>
Child JS(todoItem)
Read Only
Child to Parent Communication
Child
Event Type
Event type Naming conventions
• No uppercase letters
• No spaces
• Use underscores to separate words
• Don’t prefix your event name with string ‘on’
Parent HTML
Parent <c-display onshowdata={handleData}></c-display>
Child JS(display)
showdataHandler() {
this.dispatchEvent(new CustomEvent(‘showdata’));
}
this.dispatchEvent(new CustomEvent(‘showdata’,{detail: this.data}));
handleData(event){
myData=event.detail;
}
Parent JS
Shadow DOM
• The elements in each Lightning web component are encapsulated in a shadow tree
• This part of the DOM is called a shadow tree because it’s hidden from the document that
contains it
• The shadow tree affects how you work with CSS, events, and the DOM
• Since not all browsers that Salesforce supports implement Shadow DOM, LWC uses a
shadow DOM polyfill
<c-todo-app>
#shadow-root
<div>
<p>Your To Do List</p>
</div>
<c-todo-item>
#shadow-root
<div>
<p>Go to the store</p>
</div>
</c-todo-item>
</c-todo-app>
Shadow tree for
todoApp
Shadow tree for
todoItem
Event Propagation Phases
When you create an event, define event propagation behavior
bubbles
using two properties on the event, and composed.
bubbles
A Boolean value indicating whether the event bubbles up through
the DOM or not. Defaults to false.
composed
A Boolean value indicating whether the event can pass through
the shadow boundary. Defaults to false.
Controlling Event Propagation
bubbles: false and composed: false
The event doesn’t bubble up through the DOM and doesn’t cross the shadow boundary.
bubbles: true and composed: false
The event bubbles up through the DOM, but doesn’t cross the shadow boundary.
bubbles: true and composed: true
The event bubbles up through the DOM, crosses the shadow boundary, and continues bubbling up through
the DOM to the document root.
bubbles: false and composed: true
Lightning web components don’t use this configuration
Sample
// myComponent.js
this.dispatchEvent(
new CustomEvent('notify', { bubbles: true })
);
Lifecycle – Component creation with composition
Constructor called on
parent
Public property
pending to be
updated?
Update the
public property
value
Parent inserted into
DOM
connectedCallback
called on parent
Parent rendered
Constructor called on
child
Public property
pending to be
updated?
Child inserted into DOM
connectedCallback
called on child
Child rendered
renderedCallback called
on child
renderedCallback called
on parent
Update the
public property
value
Ye
s
Ye
s
Lifecycle – Component removed
Parent removed from
DOM
disconnectedCallback
called on parent
Child removed from
DOM
disconnectedCallback
called on child
Component to Component communication
Component Component
Publisher Subscriber
registerListener
Fire event Handle event
pubsub events Can be used in
connectedCallback
Interoperability with Aura
Coexistence and Interoperability
Aura
LWC
Aura LWC
Events
Public API
Communicate
between
components
Aura LWC
UI, Data, Security
Leverage Shared
Services
LWC and Aura components composition strategies
Nested Composition and Side-by-side Composition
Lightning App Page
Aura Component Lightning Web Component
Aura Component
Lightning Web
Component
Lightning Web
Component
Lightning Web
Component
Salesforce Org
Aura Component Events
Aura Application Events
LDS/ UI API
Lightning Event Service*
Javascript custom Events/Public API
Let’s do hands-on
Lightning Locker Service
Why LockerService?
Browser isn’t build for multitenancy:
● Only one JavaScript global object, “window”
● Only one DOM global tree of element
● CSS Stylesheet is also global
Impact on security and stability:
● Components can inject JavaScript without restriction
● ... can read other component’s rendered data
● ... can call undocumented/private APIs
● ... can style other components
The current browser security model: iframe
Advantages:
Isolate JavaScript (separate global (window) execution context)
Isolate the HTML (separate DOM)
Isolate the CSS (separate stylesheets)
Disadvantages:
Content clipping (overflow of content being clipped), scrolling
issues
Bootstrap each iframe
Complex to use
Primary Risk: Cross Site Scripting (XSS)
LockerService
Prevents:
▪ XSS and similar Security Issues
▪ Reading and accessing other component’s rendered data without restrictions
▪Components from calling undocumented/private APIs
Enable:
▪ Client side API Versioning
▪ Faster Security review
▪ Secure JS Development Practices
▪ Running 3rd party JS Frameworks like React, etc.
▪ Easily adding or removing new security features and policies
When LockerService is turned on
▪ Standard components run in “system mode”
▪ User components run in “User mode” and don’t have access to the real DOM or real “window”
object
▪ Custom component gets a custom DOM (“secureDOM”), custom Window etc.
▪ Custom components can access other Components DOM if they are in the same namespace
▪ Components can access public and documented Lightning JS APIs and not private APIs
LockerService Example
Without LockerService
• All components have
access to complete DOM
With LockerService
• Salesforce-authored components have full
access to everything
• Access Granted if the other component is
in the same namespace.
• Access Denied if the other component is in
a different namespace
• “Use strict” and CSP are enabled and
enforced for security of all components.
(Separate Enablement for CSP)
What are we protecting?
“Component
accessing a button
defined in the
Lightning
namespace”
What we enforce
▪ Strict Mode: prevents common mistakes, disable unsafe code.
▪ Content Security Policy: no unsafe-eval, no unsafe-inline, i.e.
eval(), <script>, onclick
▪ Frozen object (prevent new properties from being added):
can’t use polyfills (core-js, es6-shim), transpile your code instead.
▪ Allow some APIs: i.e. escape and unescape.
▪ Proxy some APIs: i.e. querySelectorAll() returns only your
nodes.
▪ Block some APIs: can’t create HTMLDirectoryElement
Impact on Performance
Last year, we found that the the amount of third-party libraries in use greater than expected.
As we improved security, we also focused on compatibility, then on performance.
What we know:
1. Performance impact is uneven, it depends on which APIs you use.
2. Overall impact also depends on the mix between Salesforce and Custom components.
What we are doing:
3. Improving our performance test infrastructure.
4. Making improvements to the LockerService engine and to the SafeEval.
Unit Testing
Why Automate Tests?
1. Best practice
2. Improves product quality
3. Ensures compliance with requirements
4. Prevents regressions
5. Speeds up feedback loop
6. Serves as documentation
7. Increases productivity
8. Reduces release anxiety
9.Reduces legal liability
10.Wins contracts
Test Frameworks - Jest
• Because its weak-typed language
• Works on client side.
• Faster to test Unit Tests than to browse actual application.
Why UTs are more important with JavaScript
Jest – A Delightful JavaScript Testing Framework
simple framework for testing JavaScript code.
does not depend on any other JavaScript frameworks, out-of-box and config-free
does not require DOM.
can be integrated with any CI tool.
Suites
Suites: describe Your Tests
• A test suite begins with a call to the
global Jest function describe with two
parameters: a string and a function.
• The string is a name or title for a spec
suite - usually what is being tested.
The function is a block of code that
implements the suite.
describe("A suite", function() {
it("contains spec with an expectation",
function() {
expect(true).toBe(true);
});
});
Specs
Specs are defined by calling the global
Jest function it, which, like describe
takes a string and a function.
The string is the title of the spec and the
function is the spec, or test.
A spec contains one or more
expectations that test the state of the
code.
An expectation in Jest is an assertion that
is either true or false. A spec with all true
expectations is a passing spec. A spec
with one or more false expectations is a
failing spec.
describe("A suite is just a function",
function() {
var a;
it("and so is a spec", function()
{ a = true;
expect(a).toBe(true);
});
});
Expectations
which takes a value, called the actual.
• It is chained with a Matcher function, which
takes the expected value.
• Each matcher implements a boolean
comparison between the actual value and the
expected value.
• It is responsible for reporting to Jest if the
expectation is true or false. Jest will then
pass or fail the spec.
• Any matcher can evaluate to a negative
assertion by chaining the call to expect with a
not before calling the matcher.
• Expectations are built with the function expect describe("The 'toBe' matcher compares with
===", function() {
it("and has a positive case", function()
{
expect(true).toBe(true);
});
it("and can have a negative
case", function(){
expect(false).not.toBe(true);
});
});
Setup and Teardown
• To help a test suite DRY up any
duplicated setup and teardown code, Jest
provides the global beforeEach,
afterEach, beforeAll, and afterAll
functions.
• The beforeEach function is called once
before each spec in the describe in which
it is called, and the afterEach function is
called once after each spec.
describe("A spec using beforeEach and afterEach", function()
{ var foo = 0;
beforeEach(function() {
foo += 1;
});
afterEach(function() {
foo = 0;
});
it("is just a function, so it can contain any code”,function(){
expect(foo).toEqual(1);
});
it("can have more than one expectation", function()
{ expect(foo).toEqual(1);
expect(true).toEqual(true);
});
});
The 'toBe' matcher compares with ===
The 'toEqual' matcher
The 'toMatch' matcher is for regular expressions
The 'toBeDefined' matcher compares against `undefined`
The `toBeUndefined` matcher compares against `undefined`
The 'toBeNull' matcher compares against null
The 'toBeTruthy' matcher is for boolean casting testing
The 'toBeFalsy' matcher is for boolean casting testing
The 'toContain' matcher is for finding an item in an Array
Every matcher’s criteria can be inverted by prepending .not
Frequently Used Matchers
Demo
Jest and Lightning Web Components
What to Test and How?
• test the behavior of the component in isolation
• with minimal dependencies on external components or services
✓ create an instance of the component.
✓ exercise its public API.
✓ evaluate the DOM output of the component, or use the public API to evaluate internal state.
A Sample
// createElement is what we'll use to create our component under
test import { createElement } from 'lwc';
// Import module under test by convention <namespace>/<moduleName>
import LwcHelloWorld from 'c/helloWorld';
describe('helloWorld', () => {
it('displays expected header text', () => {
const expectedText = 'Hello, Lightning web components';
// Create an instance of the component under test
const element = createElement('c-hello-world', { is: LwcHelloWorld });
// Add component to DOM (jsdom) so it renders, goes through creation
lifecycle document.body.appendChild(element);
// Find the header element we want to inspect
const header = element.shadowRoot.querySelector('h1');
// Compare the found text with the expected
value
expect(header.textContent).toBe(expectedText);
// Available "expect" APIs can be found here:
// https://facebook.github.io/jest/docs/en/expect.html
});
});
Testing Asynchronous DOM Updates
test('element does not have slds-icon class when bare', () => {
const element = createElement('one-primitive-icon', { is: PrimitiveIcon
}); document.body.appendChild(element);
element.variant = "bare";
// Use a promise to wait for asynchronous changes to the
DOM return Promise.resolve().then(() => {
expect(element.classList).not.toContain('slds-icon');
});
});
Running Jest for LWC
Install Jest and Its Dependencies into Your Project
• $ npm install
• $ npm install @salesforce/lwc-jest --save-dev
• $ npm run test:unit
and run
• npm run test:unit (from commandline)
• npm run test:unit -- --watch (continuously during development)
Additional Considerations
Integrating into CI processes
Mocks - for testing with wire service
Demo
Get Hands On with a Trailmix!
sforce.co/lwc
Modern Javascript
Developement
LWC_Workbxcgbgfbgfbfgbfgbfbfbshop_Day2.pptx

More Related Content

Similar to LWC_Workbxcgbgfbgfbfgbfgbfbfbshop_Day2.pptx

Building Apps Faster with Lightning and Winter '17
Building Apps Faster with Lightning and Winter '17Building Apps Faster with Lightning and Winter '17
Building Apps Faster with Lightning and Winter '17Mark Adcock
 
Building apps faster with lightning and winter '17
Building apps faster with lightning and winter '17Building apps faster with lightning and winter '17
Building apps faster with lightning and winter '17Salesforce Developers
 
Suisse Romande SF DG - Lightning workshop
Suisse Romande SF DG - Lightning workshopSuisse Romande SF DG - Lightning workshop
Suisse Romande SF DG - Lightning workshopGnanasekaran Thoppae
 
Spring '14 Release Developer Preview Webinar
Spring '14 Release Developer Preview WebinarSpring '14 Release Developer Preview Webinar
Spring '14 Release Developer Preview WebinarSalesforce Developers
 
Lightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An IntroductionLightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An IntroductionSalesforce Developers
 
Secure Salesforce: Lightning Components Best Practices
Secure Salesforce: Lightning Components Best PracticesSecure Salesforce: Lightning Components Best Practices
Secure Salesforce: Lightning Components Best PracticesSalesforce Developers
 
Enterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web ComponentsEnterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web ComponentsSalesforce Developers
 
Hands-on Workshop: Intermediate Development with Heroku and Force.com
Hands-on Workshop: Intermediate Development with Heroku and Force.comHands-on Workshop: Intermediate Development with Heroku and Force.com
Hands-on Workshop: Intermediate Development with Heroku and Force.comSalesforce Developers
 
Lightning components performance best practices
Lightning components performance best practicesLightning components performance best practices
Lightning components performance best practicesSalesforce Developers
 
Build and Package Lightning Components for Lightning Exchange
Build and Package Lightning Components for Lightning ExchangeBuild and Package Lightning Components for Lightning Exchange
Build and Package Lightning Components for Lightning ExchangeSalesforce Developers
 
Introduction to Developing Android Apps With the Salesforce Mobile SDK
Introduction to Developing Android Apps With the Salesforce Mobile SDKIntroduction to Developing Android Apps With the Salesforce Mobile SDK
Introduction to Developing Android Apps With the Salesforce Mobile SDKSalesforce Developers
 
Lightning Component - Components, Actions and Events
Lightning Component - Components, Actions and EventsLightning Component - Components, Actions and Events
Lightning Component - Components, Actions and EventsDurgesh Dhoot
 
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...JAX London
 
Javascript Security and Lightning Locker Service
Javascript Security and Lightning Locker ServiceJavascript Security and Lightning Locker Service
Javascript Security and Lightning Locker ServiceSalesforce Developers
 
Lightning breakout mun world tour 2015 sfsans
Lightning breakout mun world tour 2015 sfsansLightning breakout mun world tour 2015 sfsans
Lightning breakout mun world tour 2015 sfsansSalesforce Deutschland
 
Lightning Design System and Components for Visualforce Developers
Lightning Design System and Components for Visualforce DevelopersLightning Design System and Components for Visualforce Developers
Lightning Design System and Components for Visualforce DevelopersSalesforce Developers
 
Salesforce.com API Series: Service Cloud Console Deep Dive
Salesforce.com API Series: Service Cloud Console Deep DiveSalesforce.com API Series: Service Cloud Console Deep Dive
Salesforce.com API Series: Service Cloud Console Deep DiveSalesforce Developers
 

Similar to LWC_Workbxcgbgfbgfbfgbfgbfbfbshop_Day2.pptx (20)

Building Apps Faster with Lightning and Winter '17
Building Apps Faster with Lightning and Winter '17Building Apps Faster with Lightning and Winter '17
Building Apps Faster with Lightning and Winter '17
 
Building apps faster with lightning and winter '17
Building apps faster with lightning and winter '17Building apps faster with lightning and winter '17
Building apps faster with lightning and winter '17
 
Suisse Romande SF DG - Lightning workshop
Suisse Romande SF DG - Lightning workshopSuisse Romande SF DG - Lightning workshop
Suisse Romande SF DG - Lightning workshop
 
Spring '14 Release Developer Preview Webinar
Spring '14 Release Developer Preview WebinarSpring '14 Release Developer Preview Webinar
Spring '14 Release Developer Preview Webinar
 
Lightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An IntroductionLightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An Introduction
 
Secure Salesforce: Lightning Components Best Practices
Secure Salesforce: Lightning Components Best PracticesSecure Salesforce: Lightning Components Best Practices
Secure Salesforce: Lightning Components Best Practices
 
An Introduction to Lightning Web Components
An Introduction to Lightning Web ComponentsAn Introduction to Lightning Web Components
An Introduction to Lightning Web Components
 
Enterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web ComponentsEnterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web Components
 
Hands-on Workshop: Intermediate Development with Heroku and Force.com
Hands-on Workshop: Intermediate Development with Heroku and Force.comHands-on Workshop: Intermediate Development with Heroku and Force.com
Hands-on Workshop: Intermediate Development with Heroku and Force.com
 
Lightning components performance best practices
Lightning components performance best practicesLightning components performance best practices
Lightning components performance best practices
 
Build and Package Lightning Components for Lightning Exchange
Build and Package Lightning Components for Lightning ExchangeBuild and Package Lightning Components for Lightning Exchange
Build and Package Lightning Components for Lightning Exchange
 
Introduction to Developing Android Apps With the Salesforce Mobile SDK
Introduction to Developing Android Apps With the Salesforce Mobile SDKIntroduction to Developing Android Apps With the Salesforce Mobile SDK
Introduction to Developing Android Apps With the Salesforce Mobile SDK
 
Lightning Component - Components, Actions and Events
Lightning Component - Components, Actions and EventsLightning Component - Components, Actions and Events
Lightning Component - Components, Actions and Events
 
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
 
Javascript Security and Lightning Locker Service
Javascript Security and Lightning Locker ServiceJavascript Security and Lightning Locker Service
Javascript Security and Lightning Locker Service
 
Lightning breakout mun world tour 2015 sfsans
Lightning breakout mun world tour 2015 sfsansLightning breakout mun world tour 2015 sfsans
Lightning breakout mun world tour 2015 sfsans
 
Lightning Design System and Components for Visualforce Developers
Lightning Design System and Components for Visualforce DevelopersLightning Design System and Components for Visualforce Developers
Lightning Design System and Components for Visualforce Developers
 
Salesforce.com API Series: Service Cloud Console Deep Dive
Salesforce.com API Series: Service Cloud Console Deep DiveSalesforce.com API Series: Service Cloud Console Deep Dive
Salesforce.com API Series: Service Cloud Console Deep Dive
 
Lightning week - Paris DUG
Lightning week - Paris DUGLightning week - Paris DUG
Lightning week - Paris DUG
 
Force.com Friday : Intro to Apex
Force.com Friday : Intro to Apex Force.com Friday : Intro to Apex
Force.com Friday : Intro to Apex
 

Recently uploaded

Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...lizamodels9
 
rishikeshgirls.in- Rishikesh call girl.pdf
rishikeshgirls.in- Rishikesh call girl.pdfrishikeshgirls.in- Rishikesh call girl.pdf
rishikeshgirls.in- Rishikesh call girl.pdfmuskan1121w
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation SlidesKeppelCorporation
 
GD Birla and his contribution in management
GD Birla and his contribution in managementGD Birla and his contribution in management
GD Birla and his contribution in managementchhavia330
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfpollardmorgan
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Dipal Arora
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdfOrient Homes
 
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc.../:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...lizamodels9
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMANIlamathiKannappan
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130  Available With RoomVIP Kolkata Call Girl Howrah 👉 8250192130  Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Roomdivyansh0kumar0
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth MarketingShawn Pang
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Serviceankitnayak356677
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdfRenandantas16
 
VIP Call Girls Pune Kirti 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Kirti 8617697112 Independent Escort Service PuneVIP Call Girls Pune Kirti 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Kirti 8617697112 Independent Escort Service PuneCall girls in Ahmedabad High profile
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.Aaiza Hassan
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst SummitHolger Mueller
 
Eni 2024 1Q Results - 24.04.24 business.
Eni 2024 1Q Results - 24.04.24 business.Eni 2024 1Q Results - 24.04.24 business.
Eni 2024 1Q Results - 24.04.24 business.Eni
 

Recently uploaded (20)

Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
 
rishikeshgirls.in- Rishikesh call girl.pdf
rishikeshgirls.in- Rishikesh call girl.pdfrishikeshgirls.in- Rishikesh call girl.pdf
rishikeshgirls.in- Rishikesh call girl.pdf
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
 
GD Birla and his contribution in management
GD Birla and his contribution in managementGD Birla and his contribution in management
GD Birla and his contribution in management
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdf
 
Best Practices for Implementing an External Recruiting Partnership
Best Practices for Implementing an External Recruiting PartnershipBest Practices for Implementing an External Recruiting Partnership
Best Practices for Implementing an External Recruiting Partnership
 
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc.../:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMAN
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130  Available With RoomVIP Kolkata Call Girl Howrah 👉 8250192130  Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
VIP Call Girls Pune Kirti 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Kirti 8617697112 Independent Escort Service PuneVIP Call Girls Pune Kirti 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Kirti 8617697112 Independent Escort Service Pune
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst Summit
 
Eni 2024 1Q Results - 24.04.24 business.
Eni 2024 1Q Results - 24.04.24 business.Eni 2024 1Q Results - 24.04.24 business.
Eni 2024 1Q Results - 24.04.24 business.
 

LWC_Workbxcgbgfbgfbfgbfgbfbfbshop_Day2.pptx

  • 1. Lightning Web Components Developer Workshop
  • 2. Forward-Looking Statements Statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Website. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
  • 3. Agenda and Training Overview Time Section Focus 09:30 - 11:00 Component Communication Parent-Child, Child-Parent, LWC-LWC, Aura-LWC 11:00 Break Coffee Break 11:15 - 11:45 Lightning Locker Best Practices 11:45 - 12:30 Unit Testing Testing with JEST 12:30- 01:30 Lunch 01:30 - 03:00 Exercise 3 Build a bear tracking app 03:00- 03:15 Break Coffee Break 03:15 - 04:00 Exercise 3 (contd) Build a bear tracking app 04:00 - 04:30 Lightning Web Components Open Source (if time permits)
  • 5. Intercomponent Communication • Parent to Child • Child to Parent • Lightning web component to Lightning web component • Lightning web component to Aura component
  • 6. Parent to Child Communication Child @api itemName; Parent HTML Parent <c-todo-item item-name={name}></c-todo-item> Child JS(todoItem) Read Only
  • 7. Child to Parent Communication Child Event Type Event type Naming conventions • No uppercase letters • No spaces • Use underscores to separate words • Don’t prefix your event name with string ‘on’ Parent HTML Parent <c-display onshowdata={handleData}></c-display> Child JS(display) showdataHandler() { this.dispatchEvent(new CustomEvent(‘showdata’)); } this.dispatchEvent(new CustomEvent(‘showdata’,{detail: this.data})); handleData(event){ myData=event.detail; } Parent JS
  • 8. Shadow DOM • The elements in each Lightning web component are encapsulated in a shadow tree • This part of the DOM is called a shadow tree because it’s hidden from the document that contains it • The shadow tree affects how you work with CSS, events, and the DOM • Since not all browsers that Salesforce supports implement Shadow DOM, LWC uses a shadow DOM polyfill <c-todo-app> #shadow-root <div> <p>Your To Do List</p> </div> <c-todo-item> #shadow-root <div> <p>Go to the store</p> </div> </c-todo-item> </c-todo-app> Shadow tree for todoApp Shadow tree for todoItem
  • 9. Event Propagation Phases When you create an event, define event propagation behavior bubbles using two properties on the event, and composed. bubbles A Boolean value indicating whether the event bubbles up through the DOM or not. Defaults to false. composed A Boolean value indicating whether the event can pass through the shadow boundary. Defaults to false.
  • 10. Controlling Event Propagation bubbles: false and composed: false The event doesn’t bubble up through the DOM and doesn’t cross the shadow boundary. bubbles: true and composed: false The event bubbles up through the DOM, but doesn’t cross the shadow boundary. bubbles: true and composed: true The event bubbles up through the DOM, crosses the shadow boundary, and continues bubbling up through the DOM to the document root. bubbles: false and composed: true Lightning web components don’t use this configuration Sample // myComponent.js this.dispatchEvent( new CustomEvent('notify', { bubbles: true }) );
  • 11. Lifecycle – Component creation with composition Constructor called on parent Public property pending to be updated? Update the public property value Parent inserted into DOM connectedCallback called on parent Parent rendered Constructor called on child Public property pending to be updated? Child inserted into DOM connectedCallback called on child Child rendered renderedCallback called on child renderedCallback called on parent Update the public property value Ye s Ye s
  • 12. Lifecycle – Component removed Parent removed from DOM disconnectedCallback called on parent Child removed from DOM disconnectedCallback called on child
  • 13. Component to Component communication Component Component Publisher Subscriber registerListener Fire event Handle event pubsub events Can be used in connectedCallback
  • 15. Coexistence and Interoperability Aura LWC Aura LWC Events Public API Communicate between components Aura LWC UI, Data, Security Leverage Shared Services
  • 16. LWC and Aura components composition strategies Nested Composition and Side-by-side Composition Lightning App Page Aura Component Lightning Web Component Aura Component Lightning Web Component Lightning Web Component Lightning Web Component Salesforce Org Aura Component Events Aura Application Events LDS/ UI API Lightning Event Service* Javascript custom Events/Public API
  • 19. Why LockerService? Browser isn’t build for multitenancy: ● Only one JavaScript global object, “window” ● Only one DOM global tree of element ● CSS Stylesheet is also global Impact on security and stability: ● Components can inject JavaScript without restriction ● ... can read other component’s rendered data ● ... can call undocumented/private APIs ● ... can style other components
  • 20. The current browser security model: iframe Advantages: Isolate JavaScript (separate global (window) execution context) Isolate the HTML (separate DOM) Isolate the CSS (separate stylesheets) Disadvantages: Content clipping (overflow of content being clipped), scrolling issues Bootstrap each iframe Complex to use
  • 21. Primary Risk: Cross Site Scripting (XSS)
  • 22. LockerService Prevents: ▪ XSS and similar Security Issues ▪ Reading and accessing other component’s rendered data without restrictions ▪Components from calling undocumented/private APIs Enable: ▪ Client side API Versioning ▪ Faster Security review ▪ Secure JS Development Practices ▪ Running 3rd party JS Frameworks like React, etc. ▪ Easily adding or removing new security features and policies
  • 23. When LockerService is turned on ▪ Standard components run in “system mode” ▪ User components run in “User mode” and don’t have access to the real DOM or real “window” object ▪ Custom component gets a custom DOM (“secureDOM”), custom Window etc. ▪ Custom components can access other Components DOM if they are in the same namespace ▪ Components can access public and documented Lightning JS APIs and not private APIs
  • 25. Without LockerService • All components have access to complete DOM
  • 26. With LockerService • Salesforce-authored components have full access to everything • Access Granted if the other component is in the same namespace. • Access Denied if the other component is in a different namespace • “Use strict” and CSP are enabled and enforced for security of all components. (Separate Enablement for CSP)
  • 27. What are we protecting? “Component accessing a button defined in the Lightning namespace”
  • 28. What we enforce ▪ Strict Mode: prevents common mistakes, disable unsafe code. ▪ Content Security Policy: no unsafe-eval, no unsafe-inline, i.e. eval(), <script>, onclick ▪ Frozen object (prevent new properties from being added): can’t use polyfills (core-js, es6-shim), transpile your code instead. ▪ Allow some APIs: i.e. escape and unescape. ▪ Proxy some APIs: i.e. querySelectorAll() returns only your nodes. ▪ Block some APIs: can’t create HTMLDirectoryElement
  • 29. Impact on Performance Last year, we found that the the amount of third-party libraries in use greater than expected. As we improved security, we also focused on compatibility, then on performance. What we know: 1. Performance impact is uneven, it depends on which APIs you use. 2. Overall impact also depends on the mix between Salesforce and Custom components. What we are doing: 3. Improving our performance test infrastructure. 4. Making improvements to the LockerService engine and to the SafeEval.
  • 31. Why Automate Tests? 1. Best practice 2. Improves product quality 3. Ensures compliance with requirements 4. Prevents regressions 5. Speeds up feedback loop 6. Serves as documentation 7. Increases productivity 8. Reduces release anxiety 9.Reduces legal liability 10.Wins contracts
  • 33. • Because its weak-typed language • Works on client side. • Faster to test Unit Tests than to browse actual application. Why UTs are more important with JavaScript
  • 34. Jest – A Delightful JavaScript Testing Framework simple framework for testing JavaScript code. does not depend on any other JavaScript frameworks, out-of-box and config-free does not require DOM. can be integrated with any CI tool.
  • 35. Suites Suites: describe Your Tests • A test suite begins with a call to the global Jest function describe with two parameters: a string and a function. • The string is a name or title for a spec suite - usually what is being tested. The function is a block of code that implements the suite. describe("A suite", function() { it("contains spec with an expectation", function() { expect(true).toBe(true); }); });
  • 36. Specs Specs are defined by calling the global Jest function it, which, like describe takes a string and a function. The string is the title of the spec and the function is the spec, or test. A spec contains one or more expectations that test the state of the code. An expectation in Jest is an assertion that is either true or false. A spec with all true expectations is a passing spec. A spec with one or more false expectations is a failing spec. describe("A suite is just a function", function() { var a; it("and so is a spec", function() { a = true; expect(a).toBe(true); }); });
  • 37. Expectations which takes a value, called the actual. • It is chained with a Matcher function, which takes the expected value. • Each matcher implements a boolean comparison between the actual value and the expected value. • It is responsible for reporting to Jest if the expectation is true or false. Jest will then pass or fail the spec. • Any matcher can evaluate to a negative assertion by chaining the call to expect with a not before calling the matcher. • Expectations are built with the function expect describe("The 'toBe' matcher compares with ===", function() { it("and has a positive case", function() { expect(true).toBe(true); }); it("and can have a negative case", function(){ expect(false).not.toBe(true); }); });
  • 38. Setup and Teardown • To help a test suite DRY up any duplicated setup and teardown code, Jest provides the global beforeEach, afterEach, beforeAll, and afterAll functions. • The beforeEach function is called once before each spec in the describe in which it is called, and the afterEach function is called once after each spec. describe("A spec using beforeEach and afterEach", function() { var foo = 0; beforeEach(function() { foo += 1; }); afterEach(function() { foo = 0; }); it("is just a function, so it can contain any code”,function(){ expect(foo).toEqual(1); }); it("can have more than one expectation", function() { expect(foo).toEqual(1); expect(true).toEqual(true); }); });
  • 39. The 'toBe' matcher compares with === The 'toEqual' matcher The 'toMatch' matcher is for regular expressions The 'toBeDefined' matcher compares against `undefined` The `toBeUndefined` matcher compares against `undefined` The 'toBeNull' matcher compares against null The 'toBeTruthy' matcher is for boolean casting testing The 'toBeFalsy' matcher is for boolean casting testing The 'toContain' matcher is for finding an item in an Array Every matcher’s criteria can be inverted by prepending .not Frequently Used Matchers
  • 40. Demo
  • 41. Jest and Lightning Web Components
  • 42. What to Test and How? • test the behavior of the component in isolation • with minimal dependencies on external components or services ✓ create an instance of the component. ✓ exercise its public API. ✓ evaluate the DOM output of the component, or use the public API to evaluate internal state.
  • 43. A Sample // createElement is what we'll use to create our component under test import { createElement } from 'lwc'; // Import module under test by convention <namespace>/<moduleName> import LwcHelloWorld from 'c/helloWorld'; describe('helloWorld', () => { it('displays expected header text', () => { const expectedText = 'Hello, Lightning web components'; // Create an instance of the component under test const element = createElement('c-hello-world', { is: LwcHelloWorld }); // Add component to DOM (jsdom) so it renders, goes through creation lifecycle document.body.appendChild(element); // Find the header element we want to inspect const header = element.shadowRoot.querySelector('h1'); // Compare the found text with the expected value expect(header.textContent).toBe(expectedText); // Available "expect" APIs can be found here: // https://facebook.github.io/jest/docs/en/expect.html }); });
  • 44. Testing Asynchronous DOM Updates test('element does not have slds-icon class when bare', () => { const element = createElement('one-primitive-icon', { is: PrimitiveIcon }); document.body.appendChild(element); element.variant = "bare"; // Use a promise to wait for asynchronous changes to the DOM return Promise.resolve().then(() => { expect(element.classList).not.toContain('slds-icon'); }); });
  • 45. Running Jest for LWC Install Jest and Its Dependencies into Your Project • $ npm install • $ npm install @salesforce/lwc-jest --save-dev • $ npm run test:unit and run • npm run test:unit (from commandline) • npm run test:unit -- --watch (continuously during development)
  • 46. Additional Considerations Integrating into CI processes Mocks - for testing with wire service
  • 47. Demo
  • 48. Get Hands On with a Trailmix! sforce.co/lwc Modern Javascript Developement