+ Start a Discussion
Hitesh KhannaHitesh Khanna 

how to write JEST test for the following lwc? can someone help..i am new to JEST and would appreciate ur help

//Display.cls

public with sharing class Display {
    @AuraEnabled(cacheable=true)
    public static Integer total(String status){
        Return [SELECT COUNT() FROM Contract WHERE Status =: status];
    }
}




//displayTotal.html

<template>
    <lightning-card title="Total Contracts" >
        <div class="slds-m-around_medium">
            <template if:true={a.data}>
               <div class="data">
                {a.data}
               </div>
            </template>
            <template if:true={a.error}>
                <div class="data">
                    {a.error}
                   </div>                
            </template>
        </div>
        <footer>Loreum Ipsum picslum</footer>
    </lightning-card>
</template>



//displayTotal.js

import { api, LightningElement, wire } from 'lwc';
import total from '@salesforce/apex/Display.total'
export default class DisplayTotal extends LightningElement {
    @api Status;
    @wire(total,{status:'$Status'}) a;
    
}
 
Best Answer chosen by Hitesh Khanna
ravi soniravi soni

hi Hitesh,
#1. first of all, I  testJestForLwc this is my LWC cmp name you have to replace it with your LWC cmp name.
#2. make sure you created  data folder into __tests__ and in data folder you have to create contractData.json file and put 5 into them.
get ref. via below img. in this img testJestForLwc is my cmp and I created __tests__>Data>contractData.Json and put 5 into contractData.Json.
and now check I am sure this time error will gone.
and onemore in above test class testJestForLwc  replace it with your class name.

don't forget to mark it as best answer.
Thank you


User-added image

All Answers

ravi soniravi soni
hy Hitesh,
here is your test class with 100% code coverage.
import { createElement } from 'lwc';
import testJestForLwc from 'c/testJestForLwc';
import { registerApexTestWireAdapter } from '@salesforce/sfdx-lwc-jest';
import total from '@salesforce/apex/Display.total';


const mockGetContactList = require('./data/contractData.json');
console.log('mockGetContactList ==> ' + JSON.stringify(mockGetContactList));

//const mockGetContactListNoRecords = require('./data/contractError.json');

const getContactListAdapter = registerApexTestWireAdapter(total);
describe('c-wire-apex', () => {
    afterEach(() => {
      while (document.body.firstChild) {
        document.body.removeChild(document.body.firstChild);
      }
      // Prevent data saved on mocks from leaking between tests
      jest.clearAllMocks();
    });
	describe('test getContactList wire',() => {

        it('renders contact records', () => {
            const element = createElement('c-test-wire-method', {
              is: testJestForLwc
            });
            document.body.appendChild(element);
              
// Emit data from @wire
getContactListAdapter.emit(mockGetContactList);

return Promise.resolve().then(() => {
    const contactElements = element.shadowRoot.querySelector('div');
   // expect(contactElements.length).toBe(mockGetContactList.length);
   console.log('contactElements.textContent : ' + contactElements.textContent);
   console.log('mockGetContactList : ' + mockGetContactList);
   let totalRec = parseInt(contactElements.textContent, 10);
   console.log('totalRec : ' + totalRec);
    expect(totalRec).toEqual(mockGetContactList);
  });
      });

    });

   
});

If this is your first test class and you don't know how to setup jest in org then simply you need to complete {1} modules.
1. https://trailhead.salesforce.com/content/learn/modules/test-lightning-web-components/set-up-jest-testing-framework
after complete this module you will get to know that how to create jest test and then simply you need to follow below step.
#1. right click on you lwc component and create a folder '__tests__' 
#2. then again right click on you lwc component and create a New file name your folderName.test.js and 
#3. then again right click on you lwc component and create a New folder name 'Data' and in data folder create 2 files called 'contractData.json' and put 5 into that file.
#4. and in yourfolderName.test.js file paste above code.
Now question is how to run test class
#1. How to test class => npm run test:unit -t className
#2. how to check code coverage =>  run test:unit:coverage -t className

let me know if it helps you and don't forget to mark it as best answer.
Thank you
Hitesh KhannaHitesh Khanna
Hey, thanks for helping...but i am getting this error.
User-added image
ravi soniravi soni

hi Hitesh,
#1. first of all, I  testJestForLwc this is my LWC cmp name you have to replace it with your LWC cmp name.
#2. make sure you created  data folder into __tests__ and in data folder you have to create contractData.json file and put 5 into them.
get ref. via below img. in this img testJestForLwc is my cmp and I created __tests__>Data>contractData.Json and put 5 into contractData.Json.
and now check I am sure this time error will gone.
and onemore in above test class testJestForLwc  replace it with your class name.

don't forget to mark it as best answer.
Thank you


User-added image
This was selected as the best answer