Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Quit Jesting and Test your Lightning Web Components, Phillipe Ozil

143 views

Published on

This developer session introduces Lightning Web Component testing. It starts with an overview of the testing environment built around the Jest framework. We learn how the environment operates in complete isolation from the Salesforce Platform and lets you run tests locally. We then cover the basics of writing tests with a "Given, When, Then" pattern. We leave you with common patterns and tips for writing efficient tests.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Quit Jesting and Test your Lightning Web Components, Phillipe Ozil

  1. 1. Forward-Looking Statement 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. Statement under the Private Securities Litigation Reform Act of 1995
  2. 2. Agenda Testing Environment Writing Tests Common Patterns & Tips
  3. 3. Testing Environment
  4. 4. A Distinct Environment for Unit Testing Runtime environment = Salesforce Platform Production org, sandbox, scratch org... Jest + jest-lwc extension ESLint + LWC rules + + + Custom dependencies ? Unit Testing environment = Local machine Optional
  5. 5. Running Local Tests Standard JS testing Flexible configuration and popular JS tools No Platform access => testing in isolation Tests must be saved in revision control No code coverage requirement
  6. 6. Jest One of the most popular JS testing frameworks (speed, features, doc…) Works with vanilla JS and HTML (JSDOM) Open Source from Facebook Extensions for specific JS frameworks
  7. 7. Jest for Lightning Web Components: lwc-jest Jest extension that brings LWC-specific testing features ● Base Lightning Component mocks ● @Wire mocking utility
  8. 8. ESLint and Lightning Web Components rules Not required for testing but highly recommended Linting utility for JS Covers component code + test code
  9. 9. Test Environment Minimal Setup Requirements: Node.js + Salesforce DX project 1) Run these commands: 2) Add test scripts to the Node project configuration: npm init npm install npm install @salesforce/lwc-jest --save-dev "scripts": { "test:unit": "lwc-jest", "test:unit:watch": "lwc-jest --watch", "test:unit:coverage": "lwc-jest --coverage" },
  10. 10. Writing Tests
  11. 11. Adding Tests for a Component lwc hello __tests__ hello.tests.js hello.html hello.js hello.js-meta.xml
  12. 12. describe('c-hello', () => { afterEach(() => { // TODO: cleanup after tests }); it('displays greeting', () => { // TODO: run test }); }); Test File Structure Test suite Teardown instructions (optional) Test
  13. 13. A Refresher on the Testing Mindset Given Prepare test When Test behavior Then Assert expected result
  14. 14. Given – Prepare Test Most of the time: add component to the DOM + set public properties const element = createElement('recipe-contact-tile', { is: ContactTile }); element.contact = CONTACT_INPUT; document.body.appendChild(element);
  15. 15. When – Test Behavior Execute the test (click a button, enter some text, call a wire…) element.shadowRoot.querySelector('lightning-button’).click(); const inputEl = element.shadowRoot.querySelector('lightning-input'); inputEl.value = USER_INPUT; inputEl.dispatchEvent(new CustomEvent('change')); getContactListAdapter.emit(mockGetContactList);
  16. 16. Then – Assert Expected Result Assertions written with a fluent syntax expect(div.textContent).toBe(`Hello, ${EXPECTED}!`); expect(errorPanelElement).not.toBeNull(); expect(mockSelectHandler).toHaveBeenCalledTimes(1); Matchers
  17. 17. Common Patterns & Tips
  18. 18. Two Types of Tests DOM inspection tests • Covers <template> • rendering logic • events • Needed but... • no test coverage • harder to maintain Logic tests • Covers JS logic, wire calls • Test coverage
  19. 19. Naming Tests Suite name describes unit under test Test name describes scenario and expectation // Unit under test describe('c-apex-wire-method-to-property', () => { describe('getContactList @wire data', () => { // Expectation and scenario it('renders no items when no records are available', () => { }); }); });
  20. 20. Test Data Use realistic input data Use module level constants Move test data sets to .json files
  21. 21. Focus on Back-Box Testing Test public methods, templates and events first No need to reach 100% code coverage
  22. 22. Conclusion
  23. 23. What we’ve covered Local testing environment with Jest How to write behavior-driven tests Focusing on black-box testing
  24. 24. Next Steps Add Prettier Setup CI Monitor code coverage evolution
  25. 25. Resources Jest website jestjs.io Sample App Gallery (Recipes in particular) trailhead.salesforce.com/sample-gallery Salesforce Developer Blog developer.salesforce.com Trailhead trailhead.salesforce.com

×