function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
IntroAmmyIntroAmmy 

Need to write test class for my custom controller

I have created a lightning component to insert lead record in Lead object
Need to write test class for that , i am totally new in test class.
Can someone please help me to write a test class 

attaching my js code and Apex controller

InsertLeadRecordsController.js

({
    save : function(component, event, helper) {  
        var birthday = component.find("birthdate").get("v.value");
        var picl;
        //alert("picl");
        if(component.get("v.FieldsToShow")==true){
            picl = component.find("pic").get("v.value");
        //alert("picl");
        if (picl==='choose'){
            picl='';
            component.set('v.leadObj.BIIB_Relationship_With_Patient__c','');
        }
        }
        if(component.get("v.FieldsToShow")==false){
            component.set('v.leadObj.BIIB_Relationship_With_Patient__c','');
        }
        
        var reqfield1 = component.find("doccrm");
        var reqfield2 = component.find("docname");
        var reqfield3 = component.find("ck");
        var reqfield5 = component.find("fname");
        
        reqfield1.showHelpMessageIfInvalid();
        reqfield2.showHelpMessageIfInvalid();
        reqfield3.showHelpMessageIfInvalid();
        reqfield5.showHelpMessageIfInvalid();
        
        if(!reqfield1.checkValidity() || !reqfield2.checkValidity() || !reqfield3.checkValidity() || !reqfield5.checkValidity() ) {
            // Optional message if you want
            alert("Please fill out the required field."); 
            return; // Don't continue past this point
        }
        
        //To Check Email
        var emailField = component.find("email");
        var emailFieldValue = emailField.get("v.value");
        // Store Regular Expression
        var regExpEmailformat = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        
        if(!$A.util.isEmpty(emailFieldValue)){   
            if(emailFieldValue.match(regExpEmailformat))
            {
                emailField.set("v.errors", [{message: null}]);
                $A.util.removeClass(emailField, 'slds-has-error');                
            }else
            {
                $A.util.addClass(emailField, 'slds-has-error');
                emailField.set("v.errors", [{message: "Please Enter a Valid Email Address"}]);               
            }
        }
        
        if($A.util.isEmpty(component.find("lname").get("v.value"))){
            //component.set("v.hasError", true);
            alert('Last Name is required');
            return false;
        }
        
        if($A.util.isEmpty(component.find("email").get("v.value"))){
            //component.set("v.hasError", true);
            alert('Email is required');
            return false;
        }
        if($A.util.isEmpty(component.find("phone").get("v.value"))){
            //component.set("v.hasError", true);
            alert('Phone is required');
            return false;
        }
        if($A.util.isEmpty(component.find("birthdate").get("v.value"))){
            //component.set("v.hasError", true);
            alert('Birth Date is required');
            return false;
        }
        
        // it will accept two types of format yyyy-mm-dd and yyyy/mm/dd
        var optimizedBirthday = birthday.replace(/-/g, "/");
        //set date based on birthday at 01:00:00 hours GMT+0100 (CET)
        var myBirthday = new Date(optimizedBirthday);
        // set current day on 01:00:00 hours GMT+0100 (CET)
        var currentDate = new Date().toJSON().slice(0,10)+' 01:00:00';
        // calculate age comparing current date and borthday
        var myAge = ~~((Date.now(currentDate) - myBirthday) / (31557600000));
        alert(myAge);
        //var today = $A.localizationService.formatDate(Date.now(currentDate), "YYYY-MM-DD");
        var dateValue = component.get("v.leadObj.HealthCloudGA__BirthDate__c");
        if(dateValue >= currentDate){
            alert('You can not enter grater than today!');
            return false; 
        }

        if(component.get("v.FieldsToShow")==true){

        if (myAge<18 && component.find("Fulname").get("v.value")== undefined) 
        {        
            alert("Full Name Responsible is required");
            return false;  
        }
        if (myAge<18 && component.find("cpfname").get("v.value")== undefined) 
        {        
            alert("CPF Of The Person In charge is required");
            return false;  
        }

        if (myAge<18 && picl==='')
        {
            alert('Please fill the Relationship With Patient');
            return false; 
        }
        if (myAge<18 &&component.find("ck1").get("v.value")== undefined)
        {
            alert('Please Select Declaration Of Legal Responsibility');
            return false; 
        }
        }
        
        if(component.get("v.FieldsToShow1")==true){
            
            if (myAge>18 && component.find("cpfpatient").get("v.value")== undefined) 
            {        
                alert("CPF Patient is required");
                return false;  
            }
        }
    
        
        var action = component.get("c.saveLead");
        action.setParams({"leadObj":component.get("v.leadObj")});
        action.setCallback(this,function(result){
            var state = result.getState();
            if(state === 'SUCCESS'){
                // component.set("v.isShow",false);
                var leadId = result.getReturnValue();
                alert('leadId'+leadId);
                //component.reinit();
                //component.find('form').value = '';
                // component.find("FirstName").set("v.value", '');
                // component.find("birthdate").set("v.value", '');
                //alert('leadId'+leadId);
                
                window.location.href = 'https://hcdev2021-latamchatbot.cs90.force.com/Thankyoupage';
            }
  
        });

        $A.enqueueAction(action);
    },
    doInit: function(cmp) {
        var pickvar = cmp.get("c.getPickListValuesIntoList");
        pickvar.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS'){
                var list = response.getReturnValue();
                cmp.set("v.picvalue", list);
            }
            else if(state === 'ERROR'){
                //var list = response.getReturnValue();
                //component.set("v.picvalue", list);
                alert('ERROR OCCURED.');
            }
        })
        $A.enqueueAction(pickvar);
        
    },
    
    changeDate : function(component, event, helper) {
        var birthday = component.find("birthdate").get("v.value");
        var optimizedBirthday = birthday.replace(/-/g, "/");
        //set date based on birthday at 01:00:00 hours GMT+0100 (CET)
        var myBirthday = new Date(optimizedBirthday);
        // set current day on 01:00:00 hours GMT+0100 (CET)
        var currentDate = new Date().toJSON().slice(0,10)+' 01:00:00';
        // calculate age comparing current date and borthday
        var myAge = ~~((Date.now(currentDate) - myBirthday) / (31557600000));
        alert(myAge);
        
        if(myAge < 18){
            component.set("v.FieldsToShow",true);    
        }
        else if(myAge > 18){
            component.set("v.FieldsToShow",false);    
        }
        
         if(myAge > 18){
         component.set("v.FieldsToShow1",true);    
        }
         else if(myAge < 18){
         component.set("v.FieldsToShow1",false);    
        }
        
    },
    
    
    handleCheck : function(component, event, helper) {
        var newCheckBoxValue = component.find("ck").get("v.checked");
        component.set('v.leadObj.BIIB_Consent__c',newCheckBoxValue);
        console.log(newCheckBoxValue);
    },
    handleCheck1 : function(component, event, helper) {
        var newCheckBoxValue1 = component.find("ck1").get("v.checked");
        component.set('v.leadObj.BIIB_Declaration_Of_Legal_Responsibility__c',newCheckBoxValue1);
        console.log(newCheckBoxValue1);
    }
})



Apex class(WebToLeadController)

public class WebToLeadController{

@AuraEnabled
public static Id saveLead(Lead leadObj){
System.debug('@' +leadObj);
try{
   insert leadObj;
   }
   catch(exception e){
   AuraHandledException ex = new AuraHandledException(e.getMessage());
    ex.setMessage(e.getMessage());
    throw ex;
   }
   return leadObj.id;
   
}
@AuraEnabled
     
    public static List<String> getPickListValuesIntoList(){
        List<String> pickListValuesList = new List<String>();
        Schema.DescribeFieldResult fieldResult = Lead.BIIB_Relationship_With_Patient__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(pickListVal.getLabel());
            System.debug('Values in Rating are: '+pickListValuesList);
        }     
        return pickListValuesList;
    
    }
}
 
Best Answer chosen by IntroAmmy
CharuDuttCharuDutt
Hii IntroAmmy
Try Below Test Class
And Also Made Some Changes 
public class WebToLeadController{

@AuraEnabled
public static Id saveLead(Lead leadObj){
System.debug('@' +leadObj);
try{
   insert leadObj;
      if(Test.isRunningTest())
			{
				throw new dmlException();
			}    
   }
   catch(dmlException e){
   //AuraHandledException ex = new AuraHandledException(e.getMessage());
    //ex.setMessage(
    system.debug(e.getMessage());
         
    //throw ex;
     
   }
   return leadObj.id;
   
}
@AuraEnabled
     
    public static List<String> getPickListValuesIntoList(){
        List<String> pickListValuesList = new List<String>();
        Schema.DescribeFieldResult fieldResult = Lead.LeadSource.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(pickListVal.getLabel());
            System.debug('Values in Rating are: '+pickListValuesList);
        }     
        return pickListValuesList;
    
    }
}




TEST CLASS


@isTest
public class WebToLeadControllerTest {
@isTest
    public Static Void UnitTest(){
        lead ld = new lead();
        ld.LastName = 'test Lead';
        ld.Company = 'Test Company';
        ld.LeadSource = 'Open - Not Contacted';
       /*fill All the necessary Fields*/
        
           test.startTest();
        WebToLeadController.saveLead(ld);
        WebToLeadController.getPickListValuesIntoList();
           test.stopTest();
    }
}
Please Mark it As Best Answer If It Helps
Thank You!

 

All Answers

CharuDuttCharuDutt
Hii IntroAmmy
Try Below Test Class
And Also Made Some Changes 
public class WebToLeadController{

@AuraEnabled
public static Id saveLead(Lead leadObj){
System.debug('@' +leadObj);
try{
   insert leadObj;
      if(Test.isRunningTest())
			{
				throw new dmlException();
			}    
   }
   catch(dmlException e){
   //AuraHandledException ex = new AuraHandledException(e.getMessage());
    //ex.setMessage(
    system.debug(e.getMessage());
         
    //throw ex;
     
   }
   return leadObj.id;
   
}
@AuraEnabled
     
    public static List<String> getPickListValuesIntoList(){
        List<String> pickListValuesList = new List<String>();
        Schema.DescribeFieldResult fieldResult = Lead.LeadSource.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(pickListVal.getLabel());
            System.debug('Values in Rating are: '+pickListValuesList);
        }     
        return pickListValuesList;
    
    }
}




TEST CLASS


@isTest
public class WebToLeadControllerTest {
@isTest
    public Static Void UnitTest(){
        lead ld = new lead();
        ld.LastName = 'test Lead';
        ld.Company = 'Test Company';
        ld.LeadSource = 'Open - Not Contacted';
       /*fill All the necessary Fields*/
        
           test.startTest();
        WebToLeadController.saveLead(ld);
        WebToLeadController.getPickListValuesIntoList();
           test.stopTest();
    }
}
Please Mark it As Best Answer If It Helps
Thank You!

 
This was selected as the best answer
Baya AdamBaya Adam
MyArticles is a writer’s community where writers can share their stories all over the world. Signup and share your stories to all over the world. Follow your favorite writers, create groups, forums, chat, and much much more!
 
IntroAmmyIntroAmmy
Can someone please help me on that 
As I am getting exception while running the test class it is showing success but when i checked log it is throwing exception 

17:23:13.384 (2384841456)|VF_PAGE_MESSAGE|Required fields are missing: [LastName]
17:23:13.384 (2385000574)|EXCEPTION_THROWN|[7]|System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName]: [LastName]
17:23:13.384 (2386474207)|HEAP_ALLOCATE|[7]|Bytes:133
17:23:13.384 (2386565534)|VARIABLE_SCOPE_BEGIN|[11]|e|Exception|true|false
17:23:13.384 (2386805077)|VARIABLE_ASSIGNMENT|[11]|e|"common.apex.runtime.impl.DmlExecutionException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName]: [LastName]"|0x23f07a1d
17:23:13.384 (2386816626)|STATEMENT_EXECUTE|[11]
17:23:13.384 (2386818984)|STATEMENT_EXECUTE|[12]
17:23:13.384 (2386881277)|HEAP_ALLOCATE|[12]|Bytes:129
17:23:13.384 (2386906845)|USER_DEBUG|[12]|DEBUG|Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName]: [LastName]



Please see my below Apex class and test class


Apex class:
------------
public class WebToLeadController{

@AuraEnabled
public static Id saveLead(Lead leadObj){
System.debug('@' +leadObj);
try{
   insert leadObj;
 
   }
   
   catch(exception e){
   system.debug(e.getMessage());

   }
   return leadObj.id;
   
}
@AuraEnabled
     
    public static List<String> getPickListValuesIntoList(){
        List<String> pickListValuesList = new List<String>();
        Schema.DescribeFieldResult fieldResult = Lead.BIIB_Relationship_With_Patient__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(pickListVal.getLabel());
            System.debug('Values in RelationShip are: '+pickListValuesList);
        }     
        return pickListValuesList;
    
    }
}


Test class:
--------------
@IsTest (seeAllData = false) 
public class WebToLeadControllerTest {
    Public static lead l = new lead();
    @testSetup static void setup() {
        
        l.FirstName = 'Test';
        l.LastName = 'Test';
        l.Company = 'Test Company';
        l.LeadSource = 'Open - Not Contacted';       
    }
    
    @IsTest
    public Static Void saveLeadTest(){
        test.startTest();
        WebToLeadController.saveLead(l);
        WebToLeadController.getPickListValuesIntoList();
        test.stopTest();
        //System.assertNotEquals(null, [Select id from Lead where LastName='Last' limit 1].size());
    }
    @IsTest
    public Static Void getpicklisttest(){
        test.startTest();
        
        List <string> pickval = WebToLeadController.getPickListValuesIntoList();
        test.stopTest();
        System.assertNotEquals(0, pickval.size());
        
    }
}