0

I want to write JEST test for the following component:

// JS file: HTTPCalloutInLWC.js

import { LightningElement, track} from 'lwc';

// importing apex class to make callout
import getCurrencyData from '@salesforce/apex/CurrencyConversionController.retriveCurrencyConversionRates';

// Currency options
const options = [
                { label: 'USD', value: 'USD' },
                { label: 'EUR', value: 'EUR' },
                { label: 'CAD', value: 'CAD' },
                { label: 'GBP', value: 'GBP' },
                { label: 'INR', value: 'INR' }];

export default class HTTPCalloutInLWC extends LightningElement {
    @track fromCurrencyValue;
    @track toCurrencyValue;
    @track options = options;
    @track toCurrencyOptions = options;
    @track conversionData;
    
    // Getting Base currency value
    handleFromCurrencyChange(event) {
        this.fromCurrencyValue = event.detail.value;
    }

    // getting exchange currency value
    handleToCurrencyChange(event) {
        this.toCurrencyValue = event.detail.value;
    }

    // Making Callout using apex class
    handleCurrencyConversion() {
        // endpoint URL
        let endpointURL = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=' 
                                + this.fromCurrencyValue + '&to_currency=' + this.toCurrencyValue + '&apikey=4W7NZUQNJ061YHHF';
        
        // calling apex class method to make callout
        getCurrencyData({strEndPointURL : endpointURL})
        .then(data => {
        
            let objData = {
                From_Currency_Name : '',
                From_Currency_Code : '',
                To_Currency_Name : '',
                To_Currency_Code : '',
                Exchange_Rate : '',
                Last_Refersed : '',
            };

            window.console.log('jsonResponse ===> '+JSON.stringify(data));
            // retriving the response data
            let exchangeData = data['Realtime Currency Exchange Rate'];

            // adding data object
            objData.From_Currency_Code = exchangeData['1. From_Currency Code'];
            objData.From_Currency_Name = exchangeData['2. From_Currency Name'];
            objData.To_Currency_Code = exchangeData['3. To_Currency Code'];
            objData.To_Currency_Name = exchangeData['4. To_Currency Name'];
            objData.Exchange_Rate = exchangeData['5. Exchange Rate'];
            objData.Last_Refershed = exchangeData['6. Last Refreshed'];

            // adding data object to show in UI
            this.conversionData = objData;
        })
        .catch(error => {
            window.console.log('error ====> '+JSON.stringify(error));
        })
    } 
}

// APEX class: CurrencyConversionController.cls

public inherited sharing class CurrencyConversionController {

    @AuraEnabled
    public static map<String, Object> retriveCurrencyConversionRates(String strEndPointURL){
        map<String, Object> mapJsonData = new map<String, Object>();
        String strResponse = null;
        if(String.isNotBlank(strEndPointURL)) {
            HttpRequest httpRequest = new HttpRequest();  
            httpRequest.setEndpoint(strEndPointURL);

            httpRequest.setMethod('GET');   
            httpRequest.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());        
            httpRequest.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); 
            
            try {  
                Http http = new Http();   
                HttpResponse httpResponse = http.send(httpRequest);  

                while(httpResponse.getStatusCode() == 302) {
                    httpRequest.setEndpoint(httpResponse.getHeader('Location'));
                    httpResponse = new Http().send(httpRequest);
                }

                if (httpResponse.getStatusCode() == 200 ) {  
                    strResponse = httpResponse.getBody();  
                } 
                else {  
                    throw new CalloutException(httpResponse.getBody());  
                }   
            } 
            catch(Exception ex) {  
                throw ex;  
            }  
        } 

        if(!String.isBlank(strResponse)) {
            mapJsonData = (map<String, Object>)JSON.deserializeUntyped(strResponse);
            System.debug('mapJsonData ===> '+mapJsonData);
        }

        if(!mapJsonData.isEmpty()) {
            return mapJsonData;
        }
        else {
            return null;
        }
    }
}

JEST test class: HTTPCalloutInLWC.test.js

import { createElement } from 'lwc';
import retriveCurrencyConversionRates from '@salesforce/apex/CurrencyConversionController.retriveCurrencyConversionRates';
import HTTPCalloutInLWC from 'c/HTTPCalloutInLWC';

describe('c-http-callout-in-lwc', () => {
    afterEach(() => {
        // The jsdom instance is shared across test cases in a 
        // single file so reset the DOM
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });
})

describe('Test the API', () => {
    it('returns false if no data is returned by the API', () => {
        // Create initial element
        const element = createElement('c-http-callout-in-lwc', {
            is: HTTPCalloutInLWC
        });
        document.body.appendChild(element);
    })
})

The basically calls an external API to get the latest exchange rates. As you can see, I have attempted to write some JEST code but it is incomplete. Please help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.