• raSFUser
  • NEWBIE
  • 15 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 3
    Replies

I have some apex i want to run but only if Quotes are an enabled feature, i have tried to check this by doing the following.

public static Boolean sfQuotesEnabled () {
        boolean enabled;
        // sObject types to describe
        String[] types = new String[]{'Quote'};
            Schema.DescribeSobjectResult[] results;
            try{
                // Make the describe call
        		results = Schema.describeSObjects(types);
            }catch(DmlException e){
        		System.debug('sfQuotesEnabled: failed to get object type');
                enabled = false;
            }
        System.debug('Got describe information for ' + results.size() + ' sObjects.');
        
        if(results.size() > 0){
            enabled = true;          
        }
        return  enabled;
    }

Unfortunatly this is resulting in an "Entity is not org-accessible" error when i disable Quotes and the Apex falls over (does not continue to the catch) can somone help identify what my issue is / how i can do this check.
I am creating a package that can altomaticly create a quote for an opportunity and populate it with all manner of infomation (if chosen from an admin screen).

the issue is that this package will be deployed to multiple SF environments some with Quotes enabled some where Quotes are not, i dont want the package to fail on install.

Is there a was to check if quotes are enabled or refrence the Quote the apex in a manner that will not cause the package to fail if quotes are not enabled?

Hello i have a very simple LWC component that runs on a custom record, it takes in the rec id as a paramater calls apex, and displayes the response message to the user.

The issue i am having is when writing a Jest test for this i encounter errors even though my component / test is basisicly identical to the one seen in the examples: (https://github.com/trailheadapps/lwc-recipes/tree/master/force-app/main/default/lwc/apexImperativeMethod) 

 

Can anyone help me corrrect this test so that it no longer fails / causes the other tests to fail.

 

Below is the HTML of my LWC:

<template>
    <div>
        <p><b>{label.Data_Sync_Heading}</b></p>
        <p>{syncMessage}</p>
    </div>
</template>
 

Below is the .js of my LWC:

import { LightningElement, api, track } from 'lwc';
import syncData from '@salesforce/apex/DataController.syncData';
import Data_Sync_Fail from '@salesforce/label/c.Data_Sync_Fail';
import Data_Sync_Default_Message from '@salesforce/label/c.Data_Sync_Default_Message';
import Data_Sync_Heading from '@salesforce/label/c.Data_Sync_Heading';



export default class syncDataLwc extends LightningElement {
    @api recordId;
    
    @track syncMessage = Data_Sync_Default_Message;
    @track syncDone = false;

    // Expose the labels to use in the template.
    label = {
        Data_Sync_Heading
    };

    connectedCallback() {
        syncData({rec: this.recordId})
         .then (response => {
             this.syncMessage = response;
             this.syncDone = true;
         })
         .catch(() => {
             this.syncMessage = Data_Sync_Fail;
             this.syncDone = true;
         });
    }
 

Below is the .JEST test code for my LWC:

import { createElement } from 'lwc';
import syncDataLwc from 'c/syncDataLwc';
import Data_Sync_Fail from '@salesforce/label/c.Data_Sync_Fail';
import Data_Sync_Heading from '@salesforce/label/c.Data_Sync_Heading';
import syncData from '@salesforce/apex/DataController.syncData';

let element;

//mock out the text for the heading label
jest.mock("@salesforce/label/c.Data_Sync_Heading", () => {
    return { default: "Sync Data" };
}, { virtual: true });

//mock out the text for the default failure message label
jest.mock("@salesforce/label/c.Data_Sync_Fail", () => {
    return { default: "Failed to Synchronise Data. Data could be out of date." };
}, { virtual: true });





// ----- adding the apex mock causes all tests to fail, when not mocked tests work as exspected.

// Mocking syncData Apex method call
jest.mock('@salesforce/apex/DataController.syncData', () => {
     return {default: jest.fn()};
}, { virtual: true });


// Sample error for imperative Apex call
const APEX_REC_SUCCESS =  "this is a test";






describe('c-sync-Data-lwc', () => {
	
	//This line of code is necessary to reset the DOM after each block of test code
	afterEach(() => {
		while (document.body.firstChild) {
			jest.clearAllMocks();
			document.body.removeChild(document.body.firstChild);
		}
	});	

    // Helper function to wait until the microtask queue is empty. This is needed for promise
    // timing when calling imperative Apex.
    function flushPromises() {
        // eslint-disable-next-line no-undef
        return new Promise((resolve) => setImmediate(resolve));
    }
    
    //An it block describes a single test. A test represents a single functional unit that you want to test. Write the it to describe the expected behavior of that function.
    it('CUSTOM LABEL TEST: Custom label for the heading was mocked with the default value', () => {
	
		// Create initial element
		const element = createElement('c-syncDataLwc', {
			is: syncDataLwc
		});
		document.body.appendChild(element);
                        
        return flushPromises().then(() =>  {
            const paragraphs = element.shadowRoot.querySelectorAll('p');
            expect(paragraphs.length).toBe(2);

            const boldHeading = element.shadowRoot.querySelectorAll('b');
            expect(boldHeading.length).toBe(1);


            expect(boldHeading[0].textContent).toBe("Sync Data");
        });
    });



    it('APEX RETURN SUCESS: checking that the default error is used when apex call fails', () => {
               
			   
        const REC_ID = '001';
        const APEX_PARAMETERS = { rec: REC_ID };
		
		
		// Create initial element
		const element = createElement('c-syncDataLwc', {
			is: syncDataLwc
		});
		document.body.appendChild(element);
		
		// Assign mock value for resolved Apex promise
        syncData.mockResolvedValue(APEX_REC_SUCCESS);
			   
        return flushPromises().then(() =>  {

           //get the paragraphs on the html page
		   const paragraphs = element.shadowRoot.querySelectorAll('p');

			//check the text is = to the sucess mock
            expect(paragraphs[1].textContent).toBe(
                APEX_REC_SUCCESS
            );

        });
    });
});
 

 

I am creating some Jest tests for my LWC components and i am struggeling to work out how to test / mock the apex call outs, in this basic component i have one but when i add a mock for the apex it causes all tests to fail.

Could somone point me in the right direction here?

LWC js

import { LightningElement, api, track } from 'lwc';
import syncData from '@salesforce/apex/DataController.syncData';
import Data_Sync_Fail from '@salesforce/label/c.Data_Sync_Fail';
import Data_Sync_Default_Message from '@salesforce/label/c.Data_Sync_Default_Message';
import Data_Sync_Heading from '@salesforce/label/c.Data_Sync_Heading';



export default class syncDataLwc extends LightningElement {
    @api recordId;
    
    @track syncMessage = Data_Sync_Default_Message;
    @track syncDone = false;

    // Expose the labels to use in the template.
    label = {
        Data_Sync_Heading
    };

    connectedCallback() {
        syncData({rec: this.recordId})
         .then (response => {
             this.syncMessage = response;
             this.syncDone = true;
         })
         .catch(() => {
             this.syncMessage = Data_Sync_Fail;
             this.syncDone = true;
         });
    }

LWC html
<template>
    <div>
        <p><b>{label.Data_Sync_Heading}</b></p>
        <p>{syncMessage}</p>
    </div>
</template>

My current test .js
import { createElement } from 'lwc';
import syncDataLwc from 'c/syncDataLwc';
import Data_Sync_Fail from '@salesforce/label/c.Data_Sync_Fail';
import Data_Sync_Heading from '@salesforce/label/c.Data_Sync_Heading';
import syncData from '@salesforce/apex/DataController.syncData';

let element;

//mock out the text for the heading label
jest.mock("@salesforce/label/c.Data_Sync_Heading", () => {
    return { default: "Sync Data" };
}, { virtual: true });

//mock out the text for the default failure message label
jest.mock("@salesforce/label/c.Data_Sync_Fail", () => {
    return { default: "Failed to Synchronise Data. Data could be out of date." };
}, { virtual: true });



// ----- adding the apex mock causes all tests to fail, when not mocked tests work as exspected.

// Mocking syncData Apex method call
jest.mock('@salesforce/apex/DataController.syncData', () => {
     return {default: jest.fn()};
}, { virtual: true });

//This line of code is necessary to reset the DOM after each block of test code
afterEach(() => {
    while (document.body.firstChild) {
        jest.clearAllMocks();
        document.body.removeChild(document.body.firstChild);
    }
});

beforeEach(() => {
    // Create initial element
    element = createElement('c-syncDataLwc', {
        is: syncDataLwc
    });
    document.body.appendChild(element);
});




describe('c-sync-Data-lwc', () => {
    
    //An it block describes a single test. A test represents a single functional unit that you want to test. Write the it to describe the expected behavior of that function.
    it('CUSTOM LABEL TEST: Custom label for the heading was mocked with the default value', () => {
        //The test uses the imported createElement method to create an instance of the component to test,
                
        return Promise.resolve().then(() => {
            const paragraphs = element.shadowRoot.querySelectorAll('p');
            expect(paragraphs.length).toBe(2);

            const boldHeading = element.shadowRoot.querySelectorAll('b');
            expect(boldHeading.length).toBe(1);


            expect(boldHeading[0].textContent).toBe("Sync Data");

        });


    });


    it('LWC DISPLAY TEST: checking number of div, p, and b tags elements used', () => {
               
        return Promise.resolve().then(() => {
            const div = element.shadowRoot.querySelectorAll('div');
            expect(div.length).toBe(1);

            const paragraphs = element.shadowRoot.querySelectorAll('p');
            expect(paragraphs.length).toBe(2);

            const boldHeading = element.shadowRoot.querySelectorAll('b');
            expect(boldHeading.length).toBe(1);


        });


    });


    it('APEX RETURN FAIL: checking that the default error is used when apex call fails', () => {
               
        return Promise.resolve().then(() => {

		// Apex test will happen here but when i add a mock for the apex it causes all tests to fail


        });


    });



});

​​​​​​​
Im hitting an issue calling a rest endpoint hosted internaly (but can be accessed externamly tested using postman), when preforming a callout from Salesforce apex i get the following error:

salesforce Unable to tunnel through proxy. Proxy returns HTTP/1.1 403 Forbidden

I have tested the endpoint using a variaty of aplications e.g. browsers, postman, java (camel routes) and encounter no issues, so the issue seems to be confined to Salesforce / setup.

The endpoint structure i am hitting is: https:/example.com:444/int/rest/users
 
private static HttpResponse callEndpont(String url, String method, String body, Integer timeout, Map<String,String> headers) {
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        if (body != '') {
            req.setBody(body);
        }
        url = url.replace(' ', '%20');
        req.setEndpoint(url);
        req.setMethod(method);
        if (timeout != null) {
            req.setTimeout(timeout);
        }
        for (String key : headers.keySet()) {
            req.setHeader(key, headers.get(key));
        }
        
        HttpResponse resp;
        try {
            resp = http.send(req);
        }
        catch (Exception e) {
            throw new callException(e.getMessage());
        }
        
        return resp;
    }

Can anyone help me identify the problem here?

Thank you.

Hello i have toast messages that display to users based on diffrent rules, i need this test to be translatable / as well as allow overridable by system admins when the managed package is deployed.

I beleave Custom Metadata fields in conjunction with translation workbench will allow this but i have not idea how to retrieve the data in SOQL, could somone give me an example?

when i try the below all i get is an empty entry.

SELECT Label, ExampleNamespace__Ex_example_field__c FROM ExampleNamespace__Ex_example__mdt

 

I have an app that contains various toast messages based on the user selecting different options on the form, currently the messages are all hard coded and in the base language (English) however i would like to give admins the ability to modify the base text of the message as well as translate it for users in different countries. 


Is there a 'best practices' way of doing this?  

I have a LWC Combobox whos options are pulled from a List of custom objects, and this LWC Combobox is on the Opportunity page. 

The issue is that a new value can be added to the list List of custom objects via another LWC and my Combobox options are not being rereshed.

Combobox Template 
<template>
        <div class="slds-theme_default">

    <lightning-combobox
            name="defaultOption"
            label="Default Option"
            options={options}
            value={value}
            placeholder="Select Default Option"
            onchange={handleChange} >
    </lightning-combobox>

    </div>
</template>

Combobox JS
 
import { LightningElement,  api, wire, track, } from 'lwc';
import updateOpportunityDefault from '@salesforce/apex/CustomDefaultOperations.updateOpportunityDefault';
import getDefaultOptions from '@salesforce/apex/CustomDefaultOperations.getDefaultOptions';
import getDefaultSelected from '@salesforce/apex/CustomDefaultOperations.getDefaultSelected';

import {getSObjectValue} from '@salesforce/apex';


import Id from '@salesforce/schema/Custom_Object_Opp_Default__Options__c.Id';
import custom__Possible__Option__c from '@salesforce/schema/Custom_Object_Opp_Default__Options__c.custom__Possible__Option__c';
import custom__Default__Option__c from '@salesforce/schema/Opportunity.custom__Default__Option__c';


import {ShowToastEvent} from 'lightning/platformShowToastEvent';


export default class opportunityDefaultOptionLWC extends LightningElement {
    
    @track value;
    @track options; 
    @track LastDefaultSelected; // stores the last option selected sucessfuly the combobox options
    @track defaultOptionsKeyValuePair = []; // this is the list of options created by the apex call

    @api sfOppId; // Salesforce Opportunity Id

	// on init get the current default option chosen form opportunity 
    connectedCallback() {
		// call apex that querys the opportuinity and returns an opportunity list (limit 1) to get the current default value form field
        getDefaultSelected({"sfOppId":this.sfOppId})
        .then( result => {
            try{
                console.log(result);
                console.log("getDefaultSelected = " + result);
                result.forEach(element => {
                   this.LastDefaultSelected = getSObjectValue(element, custom__Default__Option__c);
                   console.log("getDefaultSelected: LastDefaultSelected = " + this.LastDefaultSelected);
                });
            }catch (err){
                console.log(err);
                console.log("getDefaultSelected: getDefaultSelected is empty, error \n" + err);
            }
        })
        .catch(error =>{
            this.error = error;
            console.log(this.error);
            console.log("getDefaultSelected: getDefaultSelected, error \n" + this.error);
        })
    }

	// on render get the list of avalible options for default.
    renderedCallback(){
        console.log("renderedCallback: LastDefaultSelected: = "+ this.LastDefaultSelected);
		// call apex that querys a custom object returns a list of all valid options for this opportunity to populat the combobox options
        getDefaultOptions({"sfOppId":this.sfOppId})
        .then( result => {
            try{
                console.log("getDefaultOptions: result from apex below -");
                console.log(result);
				
                result.forEach(element => {
                        var id = getSObjectValue(element, Id);
                        var optionValue = getSObjectValue(element, custom__Possible__Option__c);
                        this.defaultOptionsKeyValuePair.push({ value: id, label: optionValue});
                    });
                    console.log("getDefaultOptions: Options List below -");

					// log list of options generated by apex call
                    console.log(this.defaultOptionsKeyValuePair);
					
					// set combobox options to list generated
                    this.options =  this.defaultOptionsKeyValuePair;
 
            }catch (err){
                console.log(err);
                console.log("getDefaultOptions: getDefaultOptions is empty, error \n" + err);
            }
        })
        .catch(error =>{

            this.error = error;
            console.log(this.error);
            console.log("getDefaultOptions: getDefaultOptions, error \n" + this.error);
        })
        
        this.value = this.LastDefaultSelected;

    }


	//when user selects new combobox value
    handleChange(event) { 
	
        console.log("handleChange: primaryQuoteChange");	
        // log out the orignal default and user selected
		var orignalDefaultOption =  this.value;
        var userSelectedDefaultOption = event.detail.value;
        console.log("handleChange: orignal value = " + orignalDefaultOption);
        console.log("handleChange: Selected value = " + userSelectedDefaultOption);

       try{
            console.log("handleChange: opportunityId = " + this.sfOppId + " userSelectedDefaultOption = " + userSelectedDefaultOption)
            
			// call an apex class that validates the option selected is valid for default selection
			updateOpportunityDefault({"opportunityId":this.sfOppId, "userSelectedDefaultOption":userSelectedDefaultOption})
                .then(() => {
                        console.log("handleChange: default updated.");

                        this.LastDefaultSelected = userSelectedDefaultOption;
                        console.log("handleChange: response success LastDefaultSelected = " + this.LastDefaultSelected);
                        const showsuccess = new ShowToastEvent({
                            title: 'Default Option Updated',
                            message: 'The Opprtunity Default Option has been updated to ' + userSelectedDefaultOption ,
                            variant: 'success'
                        });
                        this.dispatchEvent(showsuccess);
                    })
                    .catch(error => {
                        console.log("handleChange: Default Option update failed.");
                        this.LastDefaultSelected = orignalDefaultOption;

                        console.log("handleChange: response error LastDefaultSelected = " + this.LastDefaultSelected);
                        this.value = this.LastDefaultSelected;

                        console.log(error.body);
                    

                        var message = 'Error message: ' + error.body.message;
                        

                        const showerror = new ShowToastEvent({
                            title: 'Default Option Update Failed',
                            message: message,
                            variant: 'error',
                            mode: 'sticky'
                        });
                        this.dispatchEvent(showerror);
                    });


            }catch (err){
                console.log("handleChange: handleChange, error \n" + err);
                this.LastDefaultSelected = orignalDefaultOption;
                console.log("handleChange: Error LastDefaultSelected = " + this.LastDefaultSelected);
                this.value = this.LastDefaultSelected;

            }

        }
}

How can i make the renderedCallback() retrigger or the options list regenerate when a new record is added the the Salesforce Custom Object.  

I am currently trying to complete the trailhead 'Create a Hello World Lightning Web Component' section where you deploy the lightning web component from VSCode to your org, and im hitting the below error.

Starting SFDX: Deploy Source to Org

18:12:03.382 sfdx force:source:deploy --sourcepath c:\Users\ravent\Documents\SFDX Projects\HelloWorldLightningWebComponent\force-app\main\default --json --loglevel fatal
18:12:07.153 sfdx force:source:deploy --sourcepath c:\Users\ravent\Documents\SFDX Projects\HelloWorldLightningWebComponent\force-app\main\default --json --loglevel fatal ended with exit code 1

sf:UNSUPPORTED_API_VERSION: UNSUPPORTED_API_VERSION: Invalid Api version specified on URL

 

helloWorld error

As far as i can see i have followed the instructions to the letter, and cant seem to correct the error.

Any suggestions would be greatly appreachiated.

Im hitting an issue calling a rest endpoint hosted internaly (but can be accessed externamly tested using postman), when preforming a callout from Salesforce apex i get the following error:

salesforce Unable to tunnel through proxy. Proxy returns HTTP/1.1 403 Forbidden

I have tested the endpoint using a variaty of aplications e.g. browsers, postman, java (camel routes) and encounter no issues, so the issue seems to be confined to Salesforce / setup.

The endpoint structure i am hitting is: https:/example.com:444/int/rest/users
 
private static HttpResponse callEndpont(String url, String method, String body, Integer timeout, Map<String,String> headers) {
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        if (body != '') {
            req.setBody(body);
        }
        url = url.replace(' ', '%20');
        req.setEndpoint(url);
        req.setMethod(method);
        if (timeout != null) {
            req.setTimeout(timeout);
        }
        for (String key : headers.keySet()) {
            req.setHeader(key, headers.get(key));
        }
        
        HttpResponse resp;
        try {
            resp = http.send(req);
        }
        catch (Exception e) {
            throw new callException(e.getMessage());
        }
        
        return resp;
    }

Can anyone help me identify the problem here?

Thank you.

Hello i have toast messages that display to users based on diffrent rules, i need this test to be translatable / as well as allow overridable by system admins when the managed package is deployed.

I beleave Custom Metadata fields in conjunction with translation workbench will allow this but i have not idea how to retrieve the data in SOQL, could somone give me an example?

when i try the below all i get is an empty entry.

SELECT Label, ExampleNamespace__Ex_example_field__c FROM ExampleNamespace__Ex_example__mdt

 

I am currently trying to complete the trailhead 'Create a Hello World Lightning Web Component' section where you deploy the lightning web component from VSCode to your org, and im hitting the below error.

Starting SFDX: Deploy Source to Org

18:12:03.382 sfdx force:source:deploy --sourcepath c:\Users\ravent\Documents\SFDX Projects\HelloWorldLightningWebComponent\force-app\main\default --json --loglevel fatal
18:12:07.153 sfdx force:source:deploy --sourcepath c:\Users\ravent\Documents\SFDX Projects\HelloWorldLightningWebComponent\force-app\main\default --json --loglevel fatal ended with exit code 1

sf:UNSUPPORTED_API_VERSION: UNSUPPORTED_API_VERSION: Invalid Api version specified on URL

 

helloWorld error

As far as i can see i have followed the instructions to the letter, and cant seem to correct the error.

Any suggestions would be greatly appreachiated.