Skip to content

How to Setup Jest for LWC Testing

Coding With The Force edited this page Oct 7, 2020 · 20 revisions

Install/Setup guide for Jest:

  1. Download nodejs here: Node JS Install or use chocolately and nodist if you know what you're doing: NodeJS Nodist Install Instructions

  2. Install SFDX CLI

  3. Run this command in your project to install jest for lwc: sfdx force:lightning:lwc:test:setup

     a) This command also adds the __tests__ folders to the .forceignore file which 
     makes sure its not synced to the server.
    
  4. You may need to change your execution policy since jest doesn't register as a known Windows Package currently. Open powershell as an admin and enter the following command: Set-ExecutionPolicy Unrestricted

     a) When prompted, type the value A and then hit enter
    
  5. Create a folder inside your lightning web component (or Aura Component) folder called __tests__

     a) This can be automatically done by utilizing the sfdx force:lightning:lwc:test:create command
    
     b) If your javascript or the apex it calls does callouts to external systems, also make a folder 
        called __mocks__ to put mock files/classes in. You will need to add the glob pattern
        **/__mocks__/** to your .forceignore file if you do this.
    
  6. Create tests in the __tests__ folder and name them [fileYouAreTesting].test.js

     a) This can be automatically done by utilizing the sfdx force:lightning:lwc:test:create command
    
  7. Use the cli command sfdx force:lightning:lwc:test:run to run tests inside your __tests__ folders

    a) Use the command sfdx force:lightning:lwc:test:run --watch to have jest 
       automatically run tests when they get updated. 
    

Useful Links:

sfdx-lwc-jest repo here

sfdx cli lwc command list

Salesforce Documentation on Writing Jest Tests

Clone this wiki locally