This document discusses Lightning Web Components security and testing. It begins with forward-looking statements and risks related to new functionality, products, and services. It then provides information on debugging code, including using browser tools and debugging in different modes. Finally, it discusses unit testing Lightning Web Components with Jest, including prerequisites, configuration, and an example test file.
My INSURER PTE LTD - Insurtech Innovation Award 2024
Lightning web components - Episode 4 : Security and Testing
1. Lightning Web Components
Episode 4 – Security and Testing
March 29, 2019 | 11:00 a.m. IST
Satya Sekhar
Sr. Developer Evangelist
Salesforce
Shashank Srivatsavaya
APAC Head, Developer
Relations, Salesforce
2. Forward-Looking Statement
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 Web site.
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. Go Social!
Salesforce Developers
Salesforce Developers
Salesforce Developers
The video will be posted to YouTube & the
webinar recap page (same URL as registration).
This webinar is being recorded!
@salesforcedevs
4. Have Questions?
● Don’t wait until the end to ask your question!
● Technical support will answer questions starting now.
● Respect Q&A etiquette
● Please don’t repeat questions. The support team is working their
way down the queue.
● Stick around for live Q&A at the end
● Speakers will tackle more questions at the end, time-allowing
● Head to Developer Forums
● More questions? Visit developer.salesforce.com/forums
5. Recap
Episode 1 recap
• Lightning Web Components -
Introduction
• Sample Gallery
• Component Library and Playground
• Base Lightning Components
• Developer Tooling – Salesforce CLI and
VS Code
• Lightning Web Components Demo
Episode 2 recap
• Work with Data
• Base Lightning Components which use
Lightning Data Service
• Wire service with Lightning Data
Service and UI API
• Wire service with Apex Methods
• Imperative Apex Calls
• Configuring for App Builder
6. Recap
Episode 3 recap
• Component Composition
• Inter Component Communication and
Events
• Lifecycle hooks
• Pub sub communication
• Interoperability and Co-existence with
Aura
7. Agenda
● Share JavaScript between mondules
● Static resources and custom/3rd party javascript
● Security: LightningLocker
● Debugging
● Testing with Jest
10. Work with Third-Party Libraries
Download the Library
Upload the library as static resource
LWC content security
policy requirement
Import the static resource
Import methods from
platformResourceLoader module
import resourceName from '@salesforce/resourceUrl/resourceName';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
loadScript(self, fileUrl): Promise loadStyle(self, fileUrl): Promise
Use loadScript and loadStyle
methods to load scripts and css
Implement logic in then() callback
12. Static Resources
● Static resources can be archives (such as .zip and .jar files), images, style sheets,
JavaScript, and other files
● Static Resource Name
● Can contain only underscores and alphanumeric characters
● Must be unique in your org
● Must begin with a letter
● Should not include spaces
● Should not end with an underscore, and not contain two consecutive underscores
14. Why LockerService?
● Loosely Typed, “Everything is an Object”
● DOM (Document Object Model) fully accessible
● Browser provide access to events, URL’s, cookies, etc.
● Persistence and State possible via cookies, LocalStorage, etc.
Notable aspects of Javascript
● Cross Site Scripting
Primary Risk
● Enforces security features in your code to overcome the security threats
LockerService
15. Component Level Security
Comp 1
(Vendor Salesforce)
Comp 2
(Vendor Salesforce)
Comp 3
(Vendor Salesforce)
Comp 4
(Vendor 1)
Comp 5
(Vendor 2)
Comp 5
(Vendor 3)
Components have
• DOM access to each other
• Shared access to the window
and event structures
• Access to any client side API
Lightning App(Browser)
16. Security with Lightning Locker
● JavaScript Strict Mode Enforcement
• Don’t need to specify ”use strict” in your code
• Variables must be declared before use (var, let or constant)
• To share code you must export/import variables and functions from/to modules
• The libraries you use must also work in strict mode
● DOM Access Containment
• Lightning web components can’t use window or document global properties to query DOM
● Secure Wrappers
• Lightning Locker restricts the use of global objects by wrapping it in a secure version of the
object
17. Security with Lightning Locker
● Restricted access to Salesforce Global Variables
• Blocks access to some global javascript objects that are available to other Salesforce
features such as $A, Aura, Sfdc, and sforce
● Lightning Locker Disabled for Unsupported Browsers
● Content Security Policy (W3C Standard)
• All JavaScript libraries must be uploaded to Salesforce static resources
• All external fonts, images, frames, and CSS must use an HTTPS URL
• Script tags can’t be used to load JavaScript
• Event handlers in HTML such as onClick, onChange, etc. can’t use inline JavaScript
• CSP policy violations are logged in the browser’s developer console
19. Analyze your code before you deploy
● Fix JavaScript Errors
• Lightning Web Components extension ships by default with ESLint.
• ESLint evaluates code for errors, coding best practices and more
• ESLint metadata file is automatically added to your lwc folder
• Salesforce provides different rulesets, including base, recommended and extended
● Fix HTML Template errors
• Lightning Web Components extension provides intellisense on expressions within the HTML
markup
• It provides on the fly code validation and markup validation
20. Debug the Code
Browser Tools – Chrome Developer Tools, Fire Bug(Firefox)
● Production Mode
• Debug minified JavaScript
• Inspect proxied values
● Debug Mode
• Debug unminified JavaScript
• Inspect proxied values as regular data
• Get detailed Lightning Web Component engine warnings
23. Unit Testing
What is Unit Testing ?
A software testing method to test a standalone module to determine whether it is meeting the
expected behaviour
Why Unit Testing ?
With Unit Testing, you can fix the bugs early in the Development life cycle and save costs
How to do Unit Testing?
Write/Refactor Code
Write/Refactor Test
Run Test Deploy Code
Pass
Fail
New Change
New Change
24. Testing LWC with Jest
Jest is Javascript Testing Framework with a focus on simplicity
Prerequisites: Node.js and npm
Installation: Run these commands in the top-level directory of each Salesforce DX project
• npm – Creates package.json which contains the information about your project
• npm install – Creates package-lock.json which can contain the dependencies information
• npm install @salesforce/lwc-jest --save-dev – Installs Jest and its dependencies to test Lightning web
components
Configuration:
• Update scripts block of the package.json with list of commands that you want to use for
testing.
• Create a folder named __tests__ at the top level in your component’s bundle directory. This
folder can hold all your test js files.
• Update .forceignore to contain the pattern **/__tests__/** to ensure its contents are never
saved to Salesforce.
25. Jest Test File
// hello.test.js
import { createElement } from 'lwc’;
import Hello from 'c/hello’;
describe('c-hello', () => {
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);
}
});
it('displays greeting', () => {
// Create element
const element = createElement('c-hello’, {
is: Hello
});
document.body.appendChild(element);
// Verify displayed greeting
const div = element.shadowRoot.querySelector('div’);
expect(div.textContent).toBe('Hello, World!’);
});
});
describe block defines a test suite
Describes a single test
Create the component
Add the component to
the DOM
Assertion of success
Clean up
27. Lightning Web Components – Episode 5 Finale
● Practice what we learnt
● Implement a Business scenario
● Live coding, testing, and debugging
● Best Practices
Let’s Live Code LWC
28. Get Hands On with a Trailmix!
sforce.co/lwcModern Javascript
Developement
29. Q & A
Try Trailhead: trailhead.salesforce.com
Join the conversation: @salesforcedevs
Join Trailblazer Community Group: bit.ly/webinarinapac
30. Survey
Your feedback is crucial to the success of our
webinar programs. Please fill out the survey at
the end of the webinar. Thank you!