際際滷

際際滷Share a Scribd company logo
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
 Dont 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 its 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 doesnt bubble up through the DOM and doesnt cross the shadow boundary.
bubbles: true and composed: false
The event bubbles up through the DOM, but doesnt 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 dont 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
Lets do hands-on
Lightning Locker Service
Why LockerService?
Browser isnt 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 components 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 components 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 dont 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):
cant 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: cant 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 matchers 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 (20)

PPTX
Building Apps Faster with Lightning and Winter '17
Mark Adcock
PPTX
Building apps faster with lightning and winter '17
Salesforce Developers
PPTX
Suisse Romande SF DG - Lightning workshop
Gnanasekaran Thoppae
PDF
Spring '14 Release Developer Preview Webinar
Salesforce Developers
PDF
Lightning web components - Episode 1 - An Introduction
Salesforce Developers
PDF
Secure Salesforce: Lightning Components Best Practices
Salesforce Developers
PPTX
An Introduction to Lightning Web Components
Mikkel Flindt Heisterberg
PPTX
Enterprise-grade UI with open source Lightning Web Components
Salesforce Developers
POTX
Hands-on Workshop: Intermediate Development with Heroku and Force.com
Salesforce Developers
PPTX
Lightning components performance best practices
Salesforce Developers
PPTX
Build and Package Lightning Components for Lightning Exchange
Salesforce Developers
PDF
Introduction to Developing Android Apps With the Salesforce Mobile SDK
Salesforce Developers
PPTX
Lightning Component - Components, Actions and Events
Durgesh Dhoot
PDF
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
JAX London
PDF
Javascript Security and Lightning Locker Service
Salesforce Developers
PDF
Lightning breakout mun world tour 2015 sfsans
Salesforce Deutschland
PDF
Lightning Design System and Components for Visualforce Developers
Salesforce Developers
PDF
Salesforce.com API Series: Service Cloud Console Deep Dive
Salesforce Developers
PDF
Lightning week - Paris DUG
Paris Salesforce Developer Group
PPTX
Force.com Friday : Intro to Apex
Salesforce Developers
Building Apps Faster with Lightning and Winter '17
Mark Adcock
Building apps faster with lightning and winter '17
Salesforce Developers
Suisse Romande SF DG - Lightning workshop
Gnanasekaran Thoppae
Spring '14 Release Developer Preview Webinar
Salesforce Developers
Lightning web components - Episode 1 - An Introduction
Salesforce Developers
Secure Salesforce: Lightning Components Best Practices
Salesforce Developers
An Introduction to Lightning Web Components
Mikkel Flindt Heisterberg
Enterprise-grade UI with open source Lightning Web Components
Salesforce Developers
Hands-on Workshop: Intermediate Development with Heroku and Force.com
Salesforce Developers
Lightning components performance best practices
Salesforce Developers
Build and Package Lightning Components for Lightning Exchange
Salesforce Developers
Introduction to Developing Android Apps With the Salesforce Mobile SDK
Salesforce Developers
Lightning Component - Components, Actions and Events
Durgesh Dhoot
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
JAX London
Javascript Security and Lightning Locker Service
Salesforce Developers
Lightning breakout mun world tour 2015 sfsans
Salesforce Deutschland
Lightning Design System and Components for Visualforce Developers
Salesforce Developers
Salesforce.com API Series: Service Cloud Console Deep Dive
Salesforce Developers
Lightning week - Paris DUG
Paris Salesforce Developer Group
Force.com Friday : Intro to Apex
Salesforce Developers

Recently uploaded (20)

PDF
MusicVideoTreatmentForFreebyParrisLaVon.pdf
gamilton
PPT
How Cybersecurity Training Can Protect Your Business from Costly Threats
Sam Vohra
PDF
Dr. Elie Metri-The Middle East's Rise in Global Tech
Offpage Activity
PDF
Robbie Teehan - Owns The Pro Composer
Robbie Teehan
PDF
Choosing the Right Packaging for Your Products Sriram Enterprises, Tirunelveli
SRIRAM ENTERPRISES, TIRUNELVELI
PDF
Matthew Muckey - A Distinguished Classical Trumpet Player
Matthew Muckey
PDF
Thane Stenner - A Leader In Extreme Wealth Management
Thane Stenner
PPT
Impact of Hand Block Printing Manufacturers in the Bedsheet Retail Market.ppt
Top Supplier of Bedsheet, Razai, Comforters in India - Jaipur Wholesaler
PDF
Dr. Tran Quoc Bao - The Visionary Architect Behind Ho Chi Minh Citys Rise as...
Gorman Bain Capital
PDF
Summary of Comments on Writing the House, Parts I & II.pdf
Brij Consulting, LLC
PDF
Trends in Artificial Intelligence 2025 M Meeker
EricSabandal1
PDF
Adnan Imam - A Dynamic Freelance Writer
Adnan Imam
PDF
India's Logistics Revolution: Policy & Infrastructure Driving Transport Growth
jyotirawatt0
PDF
Top 10 Best Tutor Listing Websites in India.pdf
Digital Marketing Services India
PDF
Future-Proof Your MLM Business: Whats Working Now (and Whats Not)
Epixel MLM Software
PDF
_How Freshers Can Find the Best IT Companies in Jaipur with Salarite.pdf
SALARITE
PDF
Global Media Planning and Buying Market Trends 2025
Rupal Dekate
PDF
What Are the Structure and Benefits of New Tax Form 12BAA?
SAG Infotech
PPTX
Smarter call Reporting with Callation.pptx
Callation us
PDF
Reflect, Refine & Implement In-Person Business Growth Workshop.pdf
TheoRuby
MusicVideoTreatmentForFreebyParrisLaVon.pdf
gamilton
How Cybersecurity Training Can Protect Your Business from Costly Threats
Sam Vohra
Dr. Elie Metri-The Middle East's Rise in Global Tech
Offpage Activity
Robbie Teehan - Owns The Pro Composer
Robbie Teehan
Choosing the Right Packaging for Your Products Sriram Enterprises, Tirunelveli
SRIRAM ENTERPRISES, TIRUNELVELI
Matthew Muckey - A Distinguished Classical Trumpet Player
Matthew Muckey
Thane Stenner - A Leader In Extreme Wealth Management
Thane Stenner
Impact of Hand Block Printing Manufacturers in the Bedsheet Retail Market.ppt
Top Supplier of Bedsheet, Razai, Comforters in India - Jaipur Wholesaler
Dr. Tran Quoc Bao - The Visionary Architect Behind Ho Chi Minh Citys Rise as...
Gorman Bain Capital
Summary of Comments on Writing the House, Parts I & II.pdf
Brij Consulting, LLC
Trends in Artificial Intelligence 2025 M Meeker
EricSabandal1
Adnan Imam - A Dynamic Freelance Writer
Adnan Imam
India's Logistics Revolution: Policy & Infrastructure Driving Transport Growth
jyotirawatt0
Top 10 Best Tutor Listing Websites in India.pdf
Digital Marketing Services India
Future-Proof Your MLM Business: Whats Working Now (and Whats Not)
Epixel MLM Software
_How Freshers Can Find the Best IT Companies in Jaipur with Salarite.pdf
SALARITE
Global Media Planning and Buying Market Trends 2025
Rupal Dekate
What Are the Structure and Benefits of New Tax Form 12BAA?
SAG Infotech
Smarter call Reporting with Callation.pptx
Callation us
Reflect, Refine & Implement In-Person Business Growth Workshop.pdf
TheoRuby
Ad

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 Dont 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 its 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 doesnt bubble up through the DOM and doesnt cross the shadow boundary. bubbles: true and composed: false The event bubbles up through the DOM, but doesnt 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 dont 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 isnt 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 components 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 components 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 dont 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): cant 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: cant 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 matchers 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