SlideShare a Scribd company logo
1 of 18
Download to read offline
Get Started With LWC
Testing
Keshav Caleechurn
Saint-Pierre MA, Developer User Group
Sponsor: Spoon Consulting
Agenda
- Why is testing important
- LWC JEST Framework brief
- Setup & Configuration
- Where to write test
- Code Structure
- Demo
- Test results output formats
- Questions
Testing
- Testing attempts to find and report errors
- Identify the causes and correct errors through debugging
- Not only back-end but also front-end
● Unit Testing
● End-to-End Testing
Why is testing so important?
- Avoid Regression when adding new / updating functionalities
- Reduce flaws, hence increasing quality
- Helps ‘reduce’ cost
“Any bug not detected in the design phase will cost ten times more time to detect at the coding phase
and an additional ten times more at the debugging phase.”
—Dr. Nikolai Bezroukov, The Art of Debugging
What is JEST?
- Collect code coverage information and supports mocking to help isolate tests from complex
dependencies
- Tests are only local and are saved and run independently of Salesforce
- Run fast test as it does not run in a browser or connect to an org
- Works with Babel, TypeScript, Node, React, Angular, Vue, and more projects.
Powerful tool with rich features for Writing JavaScript tests.
Installation
- Requires sfdx-lwc-jest Node Module
- The Salesforce CLI makes it easy to install Jest and its dependencies into the project
- https://trailhead.salesforce.com/en/content/learn/modules/test-lightning-web-components/set
-up-jest-testing-framework
$ sfdx force:lightning:lwc:test:setup
You are all set to
continue
Where to write JEST tests?
- force-app/main/default/lwc/unitTest/__tests__/unitTest.test.js
- Latest versions automatically create the test folder when creating a LWC
Format: NameOfComponent.test.js
Code Structure
import { createElement } from 'lwc';
import UnitTest from 'c/unitTest';
describe('c-unit-test', () => {
afterEach(() => {
// The jsdom instance is shared across test
cases in a single file so reset the DOM
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
async function flushPromises() {
return Promise.resolve();
}
it('renders unit test'
, async () => {
// Arrange
const element = createElement('c-unit-test',
{
is: UnitTest
});
// Act
document.body.appendChild(element);
// Assert element exists
const div =
element.shadowRoot.querySelector('div');
expect(element.count).toBe(0);
expect(div.textContent).toBe('Counter : 0');
});
Code Structure
import { createElement } from 'lwc';
import UnitTest from 'c/unitTest'
;
- Imports the createElement method from the lwc framework. It’s only available in
tests
- Imports the UnitTest class from the component JavaScript controller
- Starts the describe test suite block
describe('c-unit-test'
, () => { … }
afterEach(() => {
while
(document.body.firstChild) {
document.body.removeChild(document.bod
y.firstChild);
}
});
- afterEach() runs after each test in the describe block it is in
- Resets the DOM at the end if the test
- JEST uses jsdom to provide an environment that behaves much like a
browser’s DOM or document
- Each test file gets a single instance of jsdom, and changes aren’t reset between
tests inside the file
- It is a best practice to clean up between tests so that a test’s output doesn’t
affect any other test
Code Structure
it('renders unit test'
, async () => {
const element = createElement('c-unit-test',{
is: UnitTest });
document.body.appendChild(element);
const div =
element.shadowRoot.querySelector('div');
expect(element.count).toBe(0);
expect(div.textContent).toBe('Counter : 0');
});
- Creates an instance of the component and assigns
it to the constant element
- adds the element to the jsdom’s version of
document.body using the appendChild
- Attaches LWC to DOM and renders it, triggering
connectedCallback() and renderedCallback()
- Searches the DOM for a div
- Use element.shadowRoot as the parent for the
query. It's a test-only API that lets you peek across
the shadow boundary to inspect a component’s
shadow tree
- Expect @api count = 0
- Expect element contains text Counter : 0
Scripts
package.json
Sample Commands
1. $ npm run test:unit
Run all tests for your project
3. $ npm run test:unit:watch
Run Tests Continuously During
Development
NOTE:For this option, Node relies on
Git to “watch” the code.
2. $ npm run test:unit:debug
Run Tests in Jest Debug Mode
4. $ npm run test:unit:coverage
Run Tests and Display Code Coverage
Common Issue
- “Invalid sourceApiVersion” error due to an updated VS Code Extension with the latest
Salesforce release.
- error Invalid sourceApiVersion found in sfdx-project.json. Expected 53.0, found 55.0
Demo
JEST Result Formating
jest-json-reporter:
https://github.com/Vall3y/jest-json-reporter
jest-html-reporter:
https://github.com/Hargne/jest-html-rep
orter
{
"numFailedTestSuites":0,
"numFailedTests":0,
"numPassedTestSuites":1,
"numPassedTests":2,
"numPendingTestSuites":0,
"numPendingTests":0,
"numRuntimeErrorTestSuites":0,
"numTotalTestSuites":1,
"numTotalTests":2,
"snapshot":{
.
.
.
}
Questions?
Next group meetup:
How to implement a custom cell in Lightning Datatable (lightning-datatable)
Want to be a speaker, get in touch with us:
kmoothien@sharinpix.com
JEST CHILL

More Related Content

What's hot

Introduction To Dotnet
Introduction To DotnetIntroduction To Dotnet
Introduction To DotnetSAMIR BHOGAYTA
 
Working with MS Endpoint Manager
Working with MS Endpoint ManagerWorking with MS Endpoint Manager
Working with MS Endpoint ManagerGeorge Grammatikos
 
android layouts
android layoutsandroid layouts
android layoutsDeepa Rani
 
Installation of Dspace in Windows OS: A Complete Documentation
Installation of Dspace in Windows OS: A Complete DocumentationInstallation of Dspace in Windows OS: A Complete Documentation
Installation of Dspace in Windows OS: A Complete DocumentationAshok Kumar Satapathy
 
S3 Select를 통한 빠른 데이터 분석하기 - 트랙2, Community Day 2018 re:Invent 특집
S3 Select를 통한 빠른 데이터 분석하기 - 트랙2, Community Day 2018 re:Invent 특집S3 Select를 통한 빠른 데이터 분석하기 - 트랙2, Community Day 2018 re:Invent 특집
S3 Select를 통한 빠른 데이터 분석하기 - 트랙2, Community Day 2018 re:Invent 특집AWSKRUG - AWS한국사용자모임
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and EventsHenry Osborne
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The BasicsJeff Fox
 
Introduction to Google Cloud Services / Platforms
Introduction to Google Cloud Services / PlatformsIntroduction to Google Cloud Services / Platforms
Introduction to Google Cloud Services / PlatformsNilanchal
 
Web services protocols
Web services protocolsWeb services protocols
Web services protocolsJin Castor
 
Microsoft Teams Governance and Automation
Microsoft Teams Governance and AutomationMicrosoft Teams Governance and Automation
Microsoft Teams Governance and AutomationJoel Oleson
 
Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016
Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016
Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016Amazon Web Services
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationSamsil Arefin
 
All Plans Comparison - Office 365 and Microsoft 365 Plans
All Plans Comparison - Office 365 and Microsoft 365 PlansAll Plans Comparison - Office 365 and Microsoft 365 Plans
All Plans Comparison - Office 365 and Microsoft 365 PlansGetMax DMCC
 
Simple Mail Transfer Protocol
Simple Mail Transfer ProtocolSimple Mail Transfer Protocol
Simple Mail Transfer ProtocolVinod Gurram
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state managementpriya Nithya
 
SCIM presentation from CIS 2012
SCIM presentation from CIS 2012SCIM presentation from CIS 2012
SCIM presentation from CIS 2012Twobo Technologies
 
Serverless Analytics with Amazon Redshift Spectrum, AWS Glue, and Amazon Quic...
Serverless Analytics with Amazon Redshift Spectrum, AWS Glue, and Amazon Quic...Serverless Analytics with Amazon Redshift Spectrum, AWS Glue, and Amazon Quic...
Serverless Analytics with Amazon Redshift Spectrum, AWS Glue, and Amazon Quic...Amazon Web Services
 

What's hot (20)

Introduction To Dotnet
Introduction To DotnetIntroduction To Dotnet
Introduction To Dotnet
 
Working with MS Endpoint Manager
Working with MS Endpoint ManagerWorking with MS Endpoint Manager
Working with MS Endpoint Manager
 
AWS SQS SNS
AWS SQS SNSAWS SQS SNS
AWS SQS SNS
 
Asp net
Asp netAsp net
Asp net
 
android layouts
android layoutsandroid layouts
android layouts
 
Installation of Dspace in Windows OS: A Complete Documentation
Installation of Dspace in Windows OS: A Complete DocumentationInstallation of Dspace in Windows OS: A Complete Documentation
Installation of Dspace in Windows OS: A Complete Documentation
 
S3 Select를 통한 빠른 데이터 분석하기 - 트랙2, Community Day 2018 re:Invent 특집
S3 Select를 통한 빠른 데이터 분석하기 - 트랙2, Community Day 2018 re:Invent 특집S3 Select를 통한 빠른 데이터 분석하기 - 트랙2, Community Day 2018 re:Invent 특집
S3 Select를 통한 빠른 데이터 분석하기 - 트랙2, Community Day 2018 re:Invent 특집
 
Activities, Fragments, and Events
Activities, Fragments, and EventsActivities, Fragments, and Events
Activities, Fragments, and Events
 
cloud computing Multi cloud
cloud computing Multi cloudcloud computing Multi cloud
cloud computing Multi cloud
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Introduction to Google Cloud Services / Platforms
Introduction to Google Cloud Services / PlatformsIntroduction to Google Cloud Services / Platforms
Introduction to Google Cloud Services / Platforms
 
Web services protocols
Web services protocolsWeb services protocols
Web services protocols
 
Microsoft Teams Governance and Automation
Microsoft Teams Governance and AutomationMicrosoft Teams Governance and Automation
Microsoft Teams Governance and Automation
 
Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016
Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016
Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
All Plans Comparison - Office 365 and Microsoft 365 Plans
All Plans Comparison - Office 365 and Microsoft 365 PlansAll Plans Comparison - Office 365 and Microsoft 365 Plans
All Plans Comparison - Office 365 and Microsoft 365 Plans
 
Simple Mail Transfer Protocol
Simple Mail Transfer ProtocolSimple Mail Transfer Protocol
Simple Mail Transfer Protocol
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
SCIM presentation from CIS 2012
SCIM presentation from CIS 2012SCIM presentation from CIS 2012
SCIM presentation from CIS 2012
 
Serverless Analytics with Amazon Redshift Spectrum, AWS Glue, and Amazon Quic...
Serverless Analytics with Amazon Redshift Spectrum, AWS Glue, and Amazon Quic...Serverless Analytics with Amazon Redshift Spectrum, AWS Glue, and Amazon Quic...
Serverless Analytics with Amazon Redshift Spectrum, AWS Glue, and Amazon Quic...
 

Similar to Get Started with JEST for LWC Tests.pdf

Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullySpringPeople
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSKnoldus Inc.
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsPVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsAndrey Karpov
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with seleniumTzirla Rozental
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance testBryan Liu
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Puneet Kala
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
Structured Testing Framework
Structured Testing FrameworkStructured Testing Framework
Structured Testing Frameworkserzar
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS appAleks Zinevych
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with WebpackThiago Temple
 

Similar to Get Started with JEST for LWC Tests.pdf (20)

Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium Successfully
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsPVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance test
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Structured Testing Framework
Structured Testing FrameworkStructured Testing Framework
Structured Testing Framework
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS app
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with Webpack
 
Jenkins presentation
Jenkins presentationJenkins presentation
Jenkins presentation
 
Agile Swift
Agile SwiftAgile Swift
Agile Swift
 

Recently uploaded

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Get Started with JEST for LWC Tests.pdf

  • 1. Get Started With LWC Testing Keshav Caleechurn Saint-Pierre MA, Developer User Group Sponsor: Spoon Consulting
  • 2. Agenda - Why is testing important - LWC JEST Framework brief - Setup & Configuration - Where to write test - Code Structure - Demo - Test results output formats - Questions
  • 3. Testing - Testing attempts to find and report errors - Identify the causes and correct errors through debugging - Not only back-end but also front-end ● Unit Testing ● End-to-End Testing
  • 4. Why is testing so important? - Avoid Regression when adding new / updating functionalities - Reduce flaws, hence increasing quality - Helps ‘reduce’ cost “Any bug not detected in the design phase will cost ten times more time to detect at the coding phase and an additional ten times more at the debugging phase.” —Dr. Nikolai Bezroukov, The Art of Debugging
  • 5. What is JEST? - Collect code coverage information and supports mocking to help isolate tests from complex dependencies - Tests are only local and are saved and run independently of Salesforce - Run fast test as it does not run in a browser or connect to an org - Works with Babel, TypeScript, Node, React, Angular, Vue, and more projects. Powerful tool with rich features for Writing JavaScript tests.
  • 6. Installation - Requires sfdx-lwc-jest Node Module - The Salesforce CLI makes it easy to install Jest and its dependencies into the project - https://trailhead.salesforce.com/en/content/learn/modules/test-lightning-web-components/set -up-jest-testing-framework $ sfdx force:lightning:lwc:test:setup You are all set to continue
  • 7. Where to write JEST tests? - force-app/main/default/lwc/unitTest/__tests__/unitTest.test.js - Latest versions automatically create the test folder when creating a LWC Format: NameOfComponent.test.js
  • 8. Code Structure import { createElement } from 'lwc'; import UnitTest from 'c/unitTest'; describe('c-unit-test', () => { afterEach(() => { // The jsdom instance is shared across test cases in a single file so reset the DOM while (document.body.firstChild) { document.body.removeChild(document.body.firstChild); } }); async function flushPromises() { return Promise.resolve(); } it('renders unit test' , async () => { // Arrange const element = createElement('c-unit-test', { is: UnitTest }); // Act document.body.appendChild(element); // Assert element exists const div = element.shadowRoot.querySelector('div'); expect(element.count).toBe(0); expect(div.textContent).toBe('Counter : 0'); });
  • 9. Code Structure import { createElement } from 'lwc'; import UnitTest from 'c/unitTest' ; - Imports the createElement method from the lwc framework. It’s only available in tests - Imports the UnitTest class from the component JavaScript controller - Starts the describe test suite block describe('c-unit-test' , () => { … } afterEach(() => { while (document.body.firstChild) { document.body.removeChild(document.bod y.firstChild); } }); - afterEach() runs after each test in the describe block it is in - Resets the DOM at the end if the test - JEST uses jsdom to provide an environment that behaves much like a browser’s DOM or document - Each test file gets a single instance of jsdom, and changes aren’t reset between tests inside the file - It is a best practice to clean up between tests so that a test’s output doesn’t affect any other test
  • 10. Code Structure it('renders unit test' , async () => { const element = createElement('c-unit-test',{ is: UnitTest }); document.body.appendChild(element); const div = element.shadowRoot.querySelector('div'); expect(element.count).toBe(0); expect(div.textContent).toBe('Counter : 0'); }); - Creates an instance of the component and assigns it to the constant element - adds the element to the jsdom’s version of document.body using the appendChild - Attaches LWC to DOM and renders it, triggering connectedCallback() and renderedCallback() - Searches the DOM for a div - Use element.shadowRoot as the parent for the query. It's a test-only API that lets you peek across the shadow boundary to inspect a component’s shadow tree - Expect @api count = 0 - Expect element contains text Counter : 0
  • 12. Sample Commands 1. $ npm run test:unit Run all tests for your project 3. $ npm run test:unit:watch Run Tests Continuously During Development NOTE:For this option, Node relies on Git to “watch” the code. 2. $ npm run test:unit:debug Run Tests in Jest Debug Mode 4. $ npm run test:unit:coverage Run Tests and Display Code Coverage
  • 13. Common Issue - “Invalid sourceApiVersion” error due to an updated VS Code Extension with the latest Salesforce release. - error Invalid sourceApiVersion found in sfdx-project.json. Expected 53.0, found 55.0
  • 14. Demo
  • 17. Next group meetup: How to implement a custom cell in Lightning Datatable (lightning-datatable) Want to be a speaker, get in touch with us: kmoothien@sharinpix.com