Sunday, November 15, 2020

@testSetup ( Use for Set Up Test Data for an Test Class )

Hello Friends ,

Today ,we are going to disuse about a useful topic for every developer :- method with @testSetup annotation

Methods defined with the @testSetup annotation are used for creating common test records that are available for all test methods in the class.


Syntax

Test setup methods are defined in a test class, take no arguments, and return no value. The following is the syntax of a test setup method.

  1. @testSetup static void methodName() {
  2.  
  3. }

Benefits

  1. By setting up records once for the class, you don’t need to re-create records for each test method. It’s a good time saver.
  2. Reduces test execution times, especially when you’re working with many records.

Records that are created in a test setup method are available to all test methods in the test class and are rolled back at the end of test class execution


Example as to how to use the Test Setup method,

@isTest

private class SetupClassTest

{

@testSetup static void insertContact()

{

Contact cnt = new Contact();

cnt.LastName = ‘Arunkumar’;

cnt.Email = ‘testcontact@test.com’;

insert cnt;

} 

static testMethod void updateContactEmail()

{

Contact cnt = [SELECT Name, Email FROM Contact];

System.assertEquals(cnt.Email, ‘testcontact@test.com’); 

// update contact email address. This update is local to this test method only.

cnt.Email = ‘testupdated@test.com’;

update cnt; 

System.assertEquals(cnt.Email, ‘testupdated@test.com’);

// Salesforce automatically rolled back to the original value.

}

 static testMethod void verifyTheOriginalEmail()

{

Contact cnt = [SELECT Name, Email FROM Contact];

// verify the email original email address.

System.assertEquals(cnt.Email, ‘testcontact@test.com’);

}

Explanation :-

  1. In the above test class, we inserted the Contact record in the Test Setup Method. So the inserted contact record is accessible in all test methods within the test class.
  2. Test setup methods are defined in a test class, take no arguments, and return no value.
  3. If a test class contains a test setup method, the testing framework executes the test setup method first, before any test method is executed in the class.

 

Limitation

As per salesforce documentation, take a look on the below limitations before using this method,

  1. Test setup methods aren’t supported for @isTest (SeeAllData=true) annotation test classes. Hence, you can use this feature from the API version 24.0 or above.
  2. Multiple test setup methods are allowed in a test class, but the order in which they’re executed by the testing framework isn’t guaranteed.
  3. If a fatal error occurs during the execution of a test setup method, such as an exception that’s caused by a DML operation or an assertion failure, the entire test class fails, and no further tests in the class are executed.
  4. If a test setup method calls a non-test method of another class, no code coverage is calculated for the non-test method.
Related Detail:

Monday, October 26, 2020

How to Get Custom Metadata Type data Lightning Web Components(lwc) without Apex

Hello All,

Today we will talk about Custom Metadata type and how to get Cusotm Metadata Type details into to LWC without writing any apex code.

Detail about Custom Metadata type:-

1) Custom metadata are like custom settings but records in custom metadata type 
    considered as metadata rather than data.
2) Custom MetaData are mostly used to define application configurations that need to be  migrated from one environment to another, or packaged and installed.
3)we can not perform CUD Create, Update, Delete) operation on custom metadata 
   type in apex.

AS we know in Custom Object suffix is __C  but for Custom Metadata type we are using __mdt


How to Get Custom Metadata Type data Lightning Web Components(lwc) without Apex


To Achive this we can use Wire service to get record data, the Lightning Web Component uses the getRecord wire adapter.

Syntax
import { getRecord } from 'lightning/uiRecordApi';

Sample Code:-
1) create Custom Metadata type:-
2) Get into LWC

 create Custom Metadata type:

Get into LWC

myMetadata.html
    <lightning-card title="Custom Metadata Types Record Values" icon-name="standard:contact">
        <template if:true={objMetadataValues}>
            <dl class="slds-list_horizontal slds-wrap" style="margin-left: 3%;">
                <dt class="slds-item_label slds-truncate" title="First Name">Master Label</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objMetadataValues.MasterLabel}</b>                    </dd>
                <dt class="slds-item_label slds-truncate" title="Last Name">Developer Name:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objMetadataValues.DeveloperName}                </b></dd>
                <dt class="slds-item_label slds-truncate" title="Full Name">Active:</dt>
                <dd class="slds-item_detail slds-truncate"><b>{objMetadataValues.Active}</b>                        </dd>
            </dl>
        </template>
    </lightning-card>
</template>

myMetadata.js

import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
const FIELDS = [
    'MY_Account_Data__mdt.MasterLabel',
    'MY_Account_Data__mdt.DeveloperName',
    'MY_Account_Data__mdt.isActive__c',
    'MY_Account_Data__mdt.AccoutType__c',
];
export default class myMetadata extends LightningElement {   
  @track objMetadataValues = {};
    
    // using wire service getting current user data
    // HardCoded the Record Id you can dynamically pass the record id using track or api decorates
    @wire(getRecord, { recordId: 'm02B00000006hGx', fields: FIELDS })
    userData({error, data}) {
        if(data) {
            let currentData = data.fields;
            this.objMetadataValues = {
                MasterLabel : currentData.MasterLabel.value,
                DeveloperName: currentData.DeveloperName.value,
                Active: MY_Account_Data__mdt.AccoutType__c,
                   AccountType:MY_Account_Data__mdt.AccoutType__c
         
            }
        } 
        else if(error) {
            window.console.log('error ====> '+JSON.stringify(error))
        } 
    }
}

Output



Sunday, July 19, 2020

ECMAScript( JavaScript) Standards For LWC

Hello All,


In this blow we will check , standards also impact on our developing languages, Hence we need to update our coding standards so that our lightning web components are compatible with the latest web browser.

When we are talking about salesforce lightning web component, It follows the following web standards :

Web Standards For LWC :
  • Web Components
  • Templates
  • Custom Elements
  • Shadow DOM
  • Metadata
  • ECMAScript 7
  • Events
  • Standard Elements
  • Rendering

ECMAScript LWC Compatibility : 
It's a language standard for developing lightning web components, It uses ECMAScript 6 and above. This language currently supports all the latest web browser like Apple Safari, Google Chrome, Microsoft Edge.

Now, Let's talk about the important javascript standards and changes you need to before starting with Lightning Web Components.

1. Decorators
2. DispatchEvent and CustomEvent
3. QuerySelectors
4. Import/Export
5. Spread Notation
6. Slots
7. Promises
8. String Interpolation + Let/Const

Let's discuss all these standards 

1. Decorators :
Decorators tell the compiler that specific thing you need to do with the code. Just like in Aura components we use @AuraEnabled in apex code. These decorators are also called as a magic placeholder.
    Decorators we can use for LWC components are :

    @track :
    • As this helps you to communicate inside your components (no communication of values from this component), Hence this is called private reactive property.
    • The @track tells to your compiler that you need to watch between backend code and frontend activity. For Example: whenever there are changes made you need to update the front end and then you need to update that frontend variable.
    • Let's consider a simple example, When I am adding two numbers as variable a + b and result at c. As soon as I update or change the input of and we need to perform the calculation in the backend and update the frontend result in c.
    @api : 
    • It Means whenever you are developing a code its a private by default and if you want to make it public so that other things and call and reach into it, You can put @api decorator. Hence it's called public reactive property.
    @wire :
    • It is a reactive service for data.
    • It is used to connect functions and variables to data.

    These decorators are very important while implementing salesforce lightning web components.

    2. DispatchEvent and CustomEvent :
    - These DispatchEvent are also part of web standards.
    - These events can be raised from Child to Parent.
    - Very important about these events it the event will be preceded by putting Name of the event with 'on', Hence it is recommended not to write 'on' along with your event name because you are already using onchange keyword inside your markups as onchange handler.

      SYNTAX :

      childCmp.js
      -----------------------------------------------------
      const changeEvent = new CustomEvent('change', {detail: this.roles});
      this.dispatchEvent(changeEvent);
      -----------------------------------------------------

      parentCmp.html
      -----------------------------------------------------
      <c-role-filter onchange={handleRoleChange}>
      </c-role-filter
      -----------------------------------------------------

      as you can see the onchange handles the change event in the top childCmp components. Of course for passing the values between these components we will also in @api decorators in our code.

      3. QuerySelector :
      As we have already worked with client-side javascript in lightning components, where we used Document.getElementById, But sorry It will not work for you in LWC due to security issues.

      Hence instead of Document.getElementById as per new web standards, they introduced QuerySelector for LWC.

      Let's consider an example :

      card.html
      ---------------------------------------------------
      <template>
      Hey ! Welcome to this free salesforce learning platform called: {name}
      </template>
      ---------------------------------------------------
      - Defined card inside the template in markup
        card.js
        ---------------------------------------------------
        import { apiLightningElement from 'lwc';

        export deafult class card extends LightningElement {
        @api 
           name = "Salesforce Vikas"
        }
        ---------------------------------------------------
        - with @api defined value of name as 'Salesforce vikas'
          cardContainer.html
          ---------------------------------------------------
          <c-card></c-card>
          ---------------------------------------------------
          - Called that card component inside cardContainer component markup.
            cardContainer.js
            ---------------------------------------------------
            let card = this.template.querySelector("c-card");
            card.name = "SFVIKAS";
            ---------------------------------------------------
            - Inside controller with querySelector get the c-card component.
            - Then from that card variable reassigned the value as "SFVIKAS"
              OUTPUT :
              ---------------------------------------------------
              Hey ! Welcome to this free salesforce learning platform called: SFVIKAS
              ---------------------------------------------------
              - Hence the final output will be with the latest value as SFVIKAS. Cool right ? 😎
                4. Import/Export (ECMAScript 6) :
                This is the file source to help you to use external helper functions and use it here just like a libraries. 
                You can also use your own libraries, not just LWC imports. This is just a pulling outside javascript library inside lwc component.

                Like for example when we want to use api, track then we use the syntax as follows:
                ---------------------------------------------------
                import {LightningElementtrackapi} OR

                //for importing apex class functions
                import getAccountList from '@salesforce/apex/accController.getAccountList';

                //for importing from external library 
                import { flatten } from 'c/jsUtils' ;
                ---------------------------------------------------
                As well as whenever you want to export a single variable or a function then we use export syntax as follows :
                ---------------------------------------------------
                export function flatten(objprefix=[], current={}) {......}
                ---------------------------------------------------

                5. Spread Notation (ECMAScript 9) :
                - This spread notation is a way of explicitly copying data from one array into another when we are using it.
                - It can also be used to recreate array, which updates @tracked variable. 
                - Spread actually splited the frontend thing when copying values from one array to other.
                  SYNTAX :
                  ---------------------------------------------------
                  this.data = [...result1...result2];
                  ---------------------------------------------------
                  '...are used as a spread notation 

                  6. Slots :
                  • Slots is also another web standard.
                  • It allows HTML to be passed to the component.
                  Let's understand this with an example  :

                  Consider a first greeting component :

                  greeting.html
                  ---------------------------------------------------
                  <template>
                           He is from: <slot name="country"></slot>
                           We called him: <slot name="name"</slot>        
                  </template>
                  ---------------------------------------------------

                  In another component define the values.

                  greetingContainer.html
                  ---------------------------------------------------
                  <c-greeting>
                     <span slot="country"India </span>
                     <span slot="name"Salesforce Vikas</span>
                  </c-greeting>
                  ---------------------------------------------------

                  OUTPUT :
                  ---------------------------------------------------
                  He is from: India
                  We called him: Salesforce Vikas
                  ---------------------------------------------------
                  So its simply push your content inside using slots.  

                  7. Promises : 
                  • If you think data communication 'Synchronously' then this is for you. 
                  • It is nothing but wait for the things to come back and when it will come back then do something with them with this approach it promises that it will wait for the things to come back. 
                  • It represents eventually completion and failure of the task.
                  • It uses .then() .catch() .finally() to handle promise result.
                  • This is just like lightning component that what to do with a response like if success then what to do and if its error then what time we can use it.
                  Let's understand with an example :
                  ----------------------------------------------------
                  let vikasPromise = new Promise(function (resolvereject){
                        setTimeout(function(){
                        resolve('Happy learning');
                        }, 2000)
                  });
                  ---------------------------------------------------

                  ---------------------------------------------------
                  vikasPromise.then(function(result){
                       console.log('Salesforce said:' + result);
                  }).catch(reason => {
                       console.log('Promise rejected:' + reason);
                  });

                  //Console result will be  :
                  //Console > Salesforce said : Happy Learning 
                  ---------------------------------------------------

                  NOTE: If there are multiple promises then we use Promise.all to handle multiple promises.

                  The above syntax is as per ECMAScript 6 for a higher version like ECMAScript 8 the syntax is quite different as it supports Async/ Await. But the concept remains the same.

                  8. String Interpolation (ECMAScript) + Let/Const

                  In lightning AURA components, we have used concatenation lot of time to join multiple strings. But now we need to change something in the lightning web component.

                  For Example :
                  ---------------------------------------------------
                  console.log('string1'+'string2'+'string3');
                  ---------------------------------------------------
                  Now we need to change our habits and learn something called interpolation.

                  Let's understand with the help of an example :
                  ---------------------------------------------------
                  function favouriteBlogs{
                  let firstBlog = 'Salesforce Official';
                  const secondBlog = 'Vikas singh Salesforce ';

                  //Please observe the string Interpolation below 
                  console.log('My favourite blogs are ${firstBlog} and ${secondBlog}');
                  }

                  ---------------------------------------------------
                  As you can observe in the above code we need to just use ${firstBlog} instead of maintaining '+'  signs.

                  Let/Const :
                  Of course, we are familiar with var in Javascript before, but fortunately/unfortunately now we need to use Let/Const

                  Let :
                  • Whenever you want to reassign the value for any variable then we will define with Let variable. 
                  • It also signals that the variable will be used only in the block it's defined in, which is not always the entire containing function.
                  Const :
                  • Whenever you use const then the identifier won't be reassigned further. The value will remain constant.