lwc#createElement JavaScript Examples
The following examples show how to use
lwc#createElement.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: toast-manager.js From lwc-soql-builder with MIT License | 6 votes |
export function registerToastListener() {
window.addEventListener('show-toast', evt => {
const { detail } = evt;
if (!detail) {
return;
}
const { message = 'Unexpected error occured.', errors = [] } = detail;
const toast = createElement('base-toast', { is: Toast });
toast.message = message;
toast.errors = errors;
document.body.appendChild(toast);
});
}
Example #2
Source File: chart.test.js From LightningWebChartJS with MIT License | 6 votes |
describe('Chart: ChartJs library', () => {
test('Load the ChartJS static resource', () => {
const element = createElement('x-chart', {
is: Chart
});
element.type = LINE_CHART_TYPE;
document.body.appendChild(element);
Promise.resolve().then(() => {
expect(element.uuid).toBeDefined();
document.body.removeChild(element);
});
});
test('Fail Loading the ChartJS static resource', () => {
mockScriptSuccess = false;
const element = createElement('x-chart', {
is: Chart
});
element.type = LINE_CHART_TYPE;
document.body.appendChild(element);
Promise.resolve().then(() => {
expect(element.uuid).toBeDefined();
mockScriptSuccess = true;
});
});
});
Example #3
Source File: baseAttribute.test.js From LightningWebChartJS with MIT License | 6 votes |
describe('c-base-attribute', () => {
const element = createElement('x-chart', {
is: Title
});
document.body.appendChild(element);
test('disconnectedCallback', async () => {
document.body.removeChild(element);
await expect(element).not.toBe(null);
});
});
Example #4
Source File: dataset.test.js From LightningWebChartJS with MIT License | 6 votes |
describe('c-dataset lifecycle hook', () => {
let element;
beforeEach(() => {
element = createElement('x-dataset', {
is: DataSet
});
document.body.appendChild(element);
});
test('disconnectedCallback', async () => {
const element = createElement('x-dataset', {
is: DataSet
});
document.body.appendChild(element);
document.body.removeChild(element);
await expect(element).not.toBe(null);
});
test('disconnectedCallback', async () => {
const data = createElement('x-data', {
is: Data
});
element.appendChild(data);
element.removeChild(data);
await expect(element).not.toBe(null);
});
});
Example #5
Source File: testAttributeHandler.js From LightningWebChartJS with MIT License | 6 votes |
/**
* Check that the exposed property of the attribute is matching correctly the ChartJs option (getter & setter)
*/
function testChartOptions(
constructor,
listChartOptionMock,
eventName = OPTION_EVENT_NAME
) {
describe.each(listChartOptionMock)(
'Exposed property matches ChartJS option',
(item) => {
test(`${item.propertyName}`, async () => {
const element = createElement('x-test', { is: constructor });
document.body.appendChild(element);
let detail;
document.body.addEventListener(eventName, (evt) => {
detail = evt.detail;
});
element[item.propertyName] = item.propertyValue;
await expect(element[item.propertyName]).toBe(item.propertyValue);
await expect(typeof detail).toBe('object');
await expect(detail.payload).toMatchObject(item.expectedProperty);
});
}
);
}
Example #6
Source File: testAttributeHandler.js From LightningWebChartJS with MIT License | 6 votes |
/**
* Check that the DOM element can be created
*/
function testDOMElementInteraction(className) {
test(`Create DOM Element for: ${className.prototype.constructor.name}`, () => {
const element = createElement('x-test', { is: className });
document.body.appendChild(element);
expect(element).toBeDefined();
document.body.removeChild(element);
});
}
Example #7
Source File: starRatings.test.js From LightningStarRatingComponent with BSD 3-Clause "New" or "Revised" License | 6 votes |
/**
* Creates a new instance of an LWC component and assigns public properties.
*
* @param {string} name A string that specifies the type of element to be
* created.
* @param {ElementCreationOptions} options An optional object containing a
* single property named <tt>is</tt>.
* @param {Object} props An optional object of key-value pairs to assign to
* the newly created element's public properties.
* @returns The newly created element.
*/
function createElementWithProps(name, options, props = {}) {
return Object.assign(
createElement(name, options),
props,
);
}
Example #8
Source File: sampleApp.test.js From LightningWebChartJS with MIT License | 6 votes |
describe('c-sample-app-item', () => {
test('Click all the buttons', () => {
// Create initial element
const element = createElement('c-sample-app', {
is: SampleApp
});
document.body.appendChild(element);
// Return a promise to wait for any asynchronous DOM updates. Jest
// will automatically wait for the Promise chain to complete before
// ending the test and fail the test if the promise rejects.
return Promise.resolve()
.then(() => {
const buttons = [
// eslint-disable-next-line @locker/locker/distorted-element-shadow-root-getter
...element.shadowRoot.querySelectorAll(
'button.slds-button.slds-button_neutral'
)
];
buttons.forEach((button) => button.click());
buttons.reverse().forEach((button) => button.click());
})
.then(() => {
// Verify that property is correctly incremented.
expect(
// eslint-disable-next-line @locker/locker/distorted-element-shadow-root-getter
element.shadowRoot.querySelector('c-sample-app-item')
).not.toBeNull();
});
});
});
Example #9
Source File: sampleAppItem.test.js From LightningWebChartJS with MIT License | 6 votes |
describe('c-sample-app-item', () => {
test('open modal and close modal on button click', () => {
// Create initial element
const element = createElement('c-sample-app-item', {
is: SampleAppItem
});
document.body.appendChild(element);
// eslint-disable-next-line @locker/locker/distorted-element-shadow-root-getter
const openModal = element.shadowRoot.querySelector(
'p.slds-card__footer-action.slds-text-link'
);
openModal.click();
// Return a promise to wait for any asynchronous DOM updates. Jest
// will automatically wait for the Promise chain to complete before
// ending the test and fail the test if the promise rejects.
return Promise.resolve()
.then(() => {
// Verify that property is correctly incremented.
// eslint-disable-next-line @locker/locker/distorted-element-shadow-root-getter
expect(element.shadowRoot.querySelector('section')).not.toBeNull();
// eslint-disable-next-line @locker/locker/distorted-element-shadow-root-getter
const closeModal = element.shadowRoot.querySelector(
'button.slds-button.slds-button_neutral'
);
closeModal.click();
})
.then(() => {
// Verify that property is correctly incremented.
// eslint-disable-next-line @locker/locker/distorted-element-shadow-root-getter
expect(element.shadowRoot.querySelector('section')).toBeNull();
});
});
});
Example #10
Source File: samples.js From LightningWebChartJS with MIT License | 5 votes |
sampleApp = createElement('lwcc-samples', { is: SampleApp })
Example #11
Source File: scheduler.test.js From Schedul-o-matic-9000 with BSD 3-Clause "New" or "Revised" License | 5 votes |
function setupTest() {
const element = createElement("c-scheduler", {
is: Scheduler
});
document.body.appendChild(element);
return element;
}
Example #12
Source File: videoViewer.test.js From VideoViewer with BSD 3-Clause "New" or "Revised" License | 5 votes |
createComponentUnderTest = () => {
const element = createElement("c-video-preview", {
is: VideoViewer
});
document.body.appendChild(element);
return element;
}
Example #13
Source File: chartBuilder.test.js From LightningWebChartJS with MIT License | 5 votes |
describe('test property', () => {
test('flexipageRegionWidth', () => {
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
element.flexipageRegionWidth = 'test';
expect(element.flexipageRegionWidth).toEqual('test');
});
test('detailsLabels success', () => {
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
element.detailsLabels = '["test"]';
expect(element.detailsLabels).toEqual(['test']);
});
test('detailsLabels error', () => {
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
element.detailsLabels = "['test',]";
expect(element.detailsLabels).toEqual([]);
});
test('detailsLabels error', () => {
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
element.recordId = 'test';
element.soql = ':recordId';
// Validate parameters of mocked Apex call
expect(element.soql).toEqual(`'${element.recordId}'`);
});
test('detailsLabels error', () => {
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
element.recordId;
element.soql = ':recordId';
// Validate parameters of mocked Apex call
expect(element.soql).toEqual(`'${ChartBuilder.FAKE_ID}'`);
});
test('details success', () => {
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
const data = [
{ labels: 'Item1', detail: [1, 2] },
{ labels: 'Item2', detail: [9, 8] }
];
element.details = JSON.stringify(data);
return flushPromises().then(() => {
expect(element.details.length).toEqual(data.length);
});
});
test('details success with undefined data removed', () => {
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
const data = [
{ labels: 'Item1', detail: [1, 2] },
{ labels: 'Item2', detail: [9, 8] },
{ labels: 'Item3' }
];
element.details = JSON.stringify(data);
return flushPromises().then(() => {
expect(element.details.length).toEqual(2);
});
});
});
Example #14
Source File: index.js From lwc-oss-oauth with Creative Commons Zero v1.0 Universal | 5 votes |
app = createElement('my-app', { is: MyApp })
Example #15
Source File: app.test.js From lwc-oss-oauth with Creative Commons Zero v1.0 Universal | 5 votes |
describe('my-app', () => {
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);
}
});
it('contains a link to the LWC documentation with target set to _blank', () => {
const element = createElement('my-app', {
is: MyApp
});
document.body.appendChild(element);
// Get link
const linkEl = element.shadowRoot.querySelector('a');
expect(linkEl.target).toBe('_blank');
});
it('contains a link to the LWC documentation with https://', () => {
const element = createElement('my-app', {
is: MyApp
});
document.body.appendChild(element);
// Get link
const linkEl = element.shadowRoot.querySelector('a');
expect(linkEl.href).toMatch(/^https:/);
});
it('contains one active custom element my-greeting', () => {
const element = createElement('my-app', {
is: MyApp
});
document.body.appendChild(element);
// Get array of my-greeting custom elements
const greetingEls = element.shadowRoot.querySelectorAll('my-greeting');
expect(greetingEls.length).toBe(1);
});
});
Example #16
Source File: index.js From snake-game-lwc with The Unlicense | 5 votes |
app = createElement('my-app', { is: MyApp })
Example #17
Source File: oeAuraEnabledScanner.test.js From AuraEnabledScanner with BSD 3-Clause "New" or "Revised" License | 5 votes |
function setupTest() {
const element = createElement("c-oe-aura-enabled-scanner", {
is: OeAuraEnabledScanner
});
document.body.appendChild(element);
return element;
}
Example #18
Source File: objectDetailsConfig.test.js From AppRecordDetails with BSD 3-Clause "New" or "Revised" License | 5 votes |
describe("c-object-details-config", () => {
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);
}
// Prevent data saved on mocks from leaking between tests
jest.clearAllMocks();
});
describe("change this accordingly", () => {
it("getObjectInfo @wire data", () => {
const OBJECT_API_NAME_INPUT = 'ACCOUNT';
const WIRE_PARAMETER = { objectApiName: OBJECT_API_NAME_INPUT };
// Create element
var element = createElement("c-object-details-config", {
is: appSpecificLayoutConfig
});
element.objName = OBJECT_API_NAME_INPUT;
element.configData = mockGetConfigData;
document.body.appendChild(element);
getObjectInfoAdapter.emit(mockGetObjectValues);
return Promise.resolve().then(() => {
const dualPicklists = element.shadowRoot.querySelectorAll('lightning-dual-listbox');
dualPicklists.forEach(dualBox => {
dualBox.dispatchEvent(new CustomEvent('change'));
});
const sectionNames = element.shadowRoot.querySelectorAll('lightning-input');
expect(sectionNames.length).toBe(3);
window.HTMLSelectElement.prototype.checkValidity = true;
window.HTMLSelectElement.prototype.reportValidity = true;
window.HTMLInputElement.prototype.checkValidity = true;
window.HTMLInputElement.prototype.reportValidity = true;
element.dummyfn = jest.fn().mockImplementation(() => { return null; });
const addNewSection = element.shadowRoot.querySelector('lightning-button[title="Add Section"]');
addNewSection.dispatchEvent(new CustomEvent('click'));
const deleteIcon = element.shadowRoot.querySelector('lightning-button-icon');
deleteIcon.dispatchEvent(new CustomEvent('click'));
const saveBtn = element.shadowRoot.querySelector('lightning-button[title="Save"]');
saveBtn.dispatchEvent(new CustomEvent('click'));
const cancelBtn = element.shadowRoot.querySelector('lightning-button[title="Cancel"]');
cancelBtn.dispatchEvent(new CustomEvent('click'));
});
});
});
});
Example #19
Source File: chartBuilder.test.js From LightningWebChartJS with MIT License | 5 votes |
describe('call server and get chart data when', () => {
// Disconnect the component to reset the adapter. It is also
// a best practice to clean up after each test.
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
test('soql query is passed', () => {
getChartData.mockResolvedValue(MOCK_GETCHARTDATA);
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
element.detailsLabels = MOCK_GETCHARTDATA[0].labels;
element.soql =
'SELECT StageName label, Sum(Amount) value FROM Opportunity WHERE IsClosed = false WITH SECURITY ENFORCED Group By StageName LIMIT 10';
return flushPromises().then(() => {
// Validate parameters of mocked Apex call
expect(element.details).toMatchObject(RESULT_GETCHARTDATA);
});
});
test('custom handler is passed', () => {
getChartData.mockResolvedValue(MOCK_GETCHARTDATA);
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
element.handler = 'FakeHandler';
element.detailsLabels = MOCK_GETCHARTDATA[0].labels;
return flushPromises().then(() => {
flushPromises().then(() => {
// Validate parameters of mocked Apex call
expect(element.details).toMatchObject(RESULT_GETCHARTDATA);
expect(element.handler).toEqual(element.handler);
});
});
});
test('error occurs in the server side', () => {
getChartData.mockRejectedValue(APEX_ERROR);
const element = createElement('c-chartBuilder', { is: ChartBuilder });
document.body.appendChild(element);
element.handler = 'FakeHandler';
return flushPromises().then(() => {
expect(element.details).toBeNull();
});
});
});
Example #20
Source File: chart.test.js From LightningWebChartJS with MIT License | 5 votes |
// TODO: For each type of Chart: test that can be created, that contains canvas and that elements can be inserted
describe.each(CHARTS)('DOM Tests for individual charts', (chart) => {
const chartName = chart.class.prototype.constructor.name;
const element = createElement('x-chart', {
is: chart.class
});
element.setAttribute('type', chart.type);
document.body.appendChild(element);
describe('DOM Element created correctly', () => {
test(`${chartName}`, () => {
const queriedElement = element.shadowRoot.querySelector('x-chart');
expect(queriedElement).toBeDefined();
});
});
describe('Canvas exists', () => {
test(`${chartName}`, () => {
const queriedElement = element.shadowRoot.querySelector('canvas');
expect(queriedElement).toBeDefined();
});
});
describe('Chart type is correct', () => {
test(`${chartName} is of type ${chart.type}`, () => {
expect(chart.class.type).toBe(element.type);
});
});
describe('Chart accepts child-components', () => {
test(`${chartName} Accepts attribute components`, () => {
const attributeIdentifier = 'x-attribute';
const attribute = createElement(attributeIdentifier, {
is: TestAttribute
});
element.appendChild(attribute);
const queriedElement =
element.shadowRoot.querySelector(attributeIdentifier);
expect(queriedElement).toBeDefined();
});
});
});
Example #21
Source File: clusterPredict.test.js From ClusterAnalysis with BSD 3-Clause "New" or "Revised" License | 5 votes |
describe('c-cluster-predict', () => {
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);
}
// Prevent data saved on mocks from leaking between tests
jest.clearAllMocks();
});
// Helper function to wait until the microtask queue is empty. This is needed for promise
// timing when calling imperative Apex.
let flushPromises = function() {
// eslint-disable-next-line no-undef
return new Promise((resolve) => setImmediate(resolve));
};
it('Test lookup UI rendering', () => {
getPredictUiModel.mockResolvedValue(PREDICT_SEARCHUI_SUCCESS);
const element = createElement('c-cluster-predict', {
is: ClusterPredict
});
document.body.appendChild(element);
return flushPromises().then(() => {
// check if c-lookup was created
const lookup = element.shadowRoot.querySelectorAll(
'c-lookup'
);
expect(lookup[0]).toBeDefined();
});
});
it('Test model picker UI rendering', () => {
getPredictUiModel.mockResolvedValue(PREDICT_MODELUI_SUCCESS);
const element = createElement('c-cluster-predict', {
is: ClusterPredict
});
document.body.appendChild(element);
return flushPromises().then(() => {
// check if c-lookup was created
const verticalNav = element.shadowRoot.querySelectorAll(
'lightning-vertical-navigation'
);
expect(verticalNav[0]).toBeDefined();
// check if c-lookup was created
const lookup = element.shadowRoot.querySelectorAll(
'c-lookup'
);
expect(lookup[0]).toBeUndefined();
const errorText = element.shadowRoot.querySelectorAll(
'div.slds-text-color_destructive'
);
expect(errorText[0].textContent).toBe('');
});
});
it('Test error handling', () => {
getPredictUiModel.mockRejectedValue(PREDICT_MODEL_ERROR);
const element = createElement('c-cluster-predict', {
is: ClusterPredict
});
document.body.appendChild(element);
return flushPromises().then(() => {
// Select div for validating conditionally changed text content
const errorText = element.shadowRoot.querySelectorAll(
'div.slds-text-color_destructive'
);
expect(errorText[0].textContent).toBe(PREDICT_MODEL_ERROR.body.message);
});
});
});
Example #22
Source File: drawAnnotationCanvas.test.js From DrawAnnotations with BSD 3-Clause "New" or "Revised" License | 5 votes |
describe('c-draw-annotation-canvas', () => {
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);
}
});
function flushPromises() {
// eslint-disable-next-line no-undef
return new Promise((resolve) => setImmediate(resolve));
}
it('Basic creation of canvas from No Context', () => {
DrawAnnotationCanvas.canvasWidth = 50;
DrawAnnotationCanvas.canvasHeight = 50;
DrawAnnotationCanvas.fireAutoSave = false;
const element = createElement('c-draw-annotation-canvas', {
is: DrawAnnotationCanvas
});
document.body.appendChild(element);
element.interactionMode(element.stampingMode);
expect(element.isStampingMode).toBeTruthy();
element.interactionMode(element.drawingMode);
expect(element.isDrawingMode).toBeTruthy();
element.interactionMode(element.fullMode);
expect(element.isFullMode).toBeTruthy();
element.currentCanvasValue = "{}";
expect(element.currentCanvasValue).toBeTruthy();
expect(element.currentCanvasPng).toBeFalsy();
element.backgroundImage = "Codey.png";
expect(element.backgroundImage).toBeTruthy();
element.interactionMode(element.fullMode);
element.addStampOption("Burst", "<svg></svg>");
//expect(element.hasStamps).toBeTruthy();
//return Promise.resolve().then(() => {
return flushPromises().then(() => {
const div = element.shadowRoot.querySelector(".draw-annotation-wrapper");
expect(div.firstChild).not.toBeNull();
});
});
});
Example #23
Source File: drawAnnotation.test.js From DrawAnnotations with BSD 3-Clause "New" or "Revised" License | 5 votes |
/*
let mockScriptSuccess = true;
jest.mock(
'lightning/platformResourceLoader',
() => {
return {
loadScript() {
return new Promise((resolve, reject) => {
// If the variable is false we're simulating an error when loading
// the script resource.
if (!mockScriptSuccess) {
reject('Could not load script');
} else {
global.fabric = require('../../../staticresources/fabric363/fabric.js');
resolve();
}
});
}
};
},
{ virtual: true }
);
*/
describe('c-draw-annotation', () => {
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);
}
});
function flushPromises() {
// eslint-disable-next-line no-undef
return new Promise((resolve) => setImmediate(resolve));
}
it('Basic creation of canvas from Record Context', () => {
DrawAnnotation.recordId = "a001h000003htBmAAI";
DrawAnnotation.objectApiName = "Drawing__c";
DrawAnnotation.canvasWidth = 50;
DrawAnnotation.canvasHeight = 50;
DrawAnnotation.autoLoad = false;
DrawAnnotation.autoSave = false;
const element = createElement('c-draw-annotation', {
is: DrawAnnotation
});
document.body.appendChild(element);
const flowHandler = jest.fn();
element.addEventListener(FlowAttributeChangeEvent, flowHandler);
getRecordWireAdapter.emit(mockGetRecord);
DrawAnnotation.fieldName = "Drawing__c";
getStampsAdapter.emit(mockGetStamps);
//return Promise.resolve().then(() => {
return flushPromises().then(() => {
expect(element.stampsAdded).toBeGreaterThan(0);
const el = element.shadowRoot.querySelector(".da-canvas");
expect(el).not.toBeNull();
});
});
});
Example #24
Source File: clusterPredictResult.test.js From ClusterAnalysis with BSD 3-Clause "New" or "Revised" License | 5 votes |
describe('c-cluster-predict-result', () => {
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);
}
// Prevent data saved on mocks from leaking between tests
jest.clearAllMocks();
});
// Helper function to wait until the microtask queue is empty. This is needed for promise
// timing when calling imperative Apex.
let flushPromises = function() {
// eslint-disable-next-line no-undef
return new Promise((resolve) => setImmediate(resolve));
};
it('Test predict UI rendering and calculations', () => {
predict.mockResolvedValue(PREDICT_RESULT_SUCCESS);
const element = createElement('c-cluster-predict-result', {
is: ClusterPredictResult
});
element.jobOrModel = 'a023B000003CvAEQA0';
element.recordId = '00Q3B000006d55pUAA';
element.hideHeader = false;
document.body.appendChild(element);
//element.predict();
return flushPromises().then(() => {
// Select div for validating conditionally changed text content
const dl = element.shadowRoot.querySelectorAll(
'dl.slds-dl_horizontal'
);
expect(dl).not.toBeNull();
const clusterElement = element.shadowRoot.querySelectorAll(
'dd.predict-heading-value a'
);
expect(clusterElement).not.toBeNull();
const predictionHeaderElement = element.shadowRoot.querySelectorAll('span.slds-card__header-link');
expect(predictionHeaderElement).not.toBeNull();
expect(predictionHeaderElement[0].textContent).toBe('Industry');
});
});
it('Test error handling', () => {
predict.mockRejectedValue(PREDICT_RESULT_ERROR);
const element = createElement('c-cluster-predict-result', {
is: ClusterPredictResult
});
element.jobOrModel = 'a023B000003CvAEQA0';
element.recordId = '00Q3B000006d55pUAA';
document.body.appendChild(element);
return flushPromises().then(() => {
// Select div for validating conditionally changed text content
const errorText = element.shadowRoot.querySelectorAll(
'div.slds-text-color_destructive'
);
expect(errorText[0].textContent).toBe(PREDICT_RESULT_ERROR.body.message);
});
});
});
Example #25
Source File: chart.test.js From LightningWebChartJS with MIT License | 5 votes |
describe('Chart: property', () => {
const element = createElement('x-chart', { is: Chart });
document.body.appendChild(element);
describe.each(TEST_DATA_PROPERTIES)('matches options', (item) => {
test(`${item.propertyName}`, async () => {
element[item.propertyName] = item.propertyValue;
await expect(element[item.propertyName]).toBe(item.propertyValue);
});
});
test('Accept uuid', () => {
element.uuid = 'xyz';
expect(element.uuid).toBe('xyz');
});
test('Accept canvasOnchange', () => {
element.canvasOnchange = {};
expect(element.canvasOnchange).toEqual({});
});
test('Accept canvasOnclick', () => {
element.canvasOnclick = {};
expect(element.canvasOnclick).toEqual({});
});
test('Accept canvasOnmouseover', () => {
element.canvasOnmouseover = {};
expect(element.canvasOnmouseover).toEqual({});
});
test('Accept canvasOnmouseout', () => {
element.canvasOnmouseout = {};
expect(element.canvasOnmouseout).toEqual({});
});
test('chartjsLoadedCallback was called', async () => {
let chartjsCb = jest.fn();
element.chartjsloadedCallback = chartjsCb;
return flushPromises().then(() => {
expect(chartjsCb).toBeCalled();
expect(element.chartjsloadedCallback).toEqual(chartjsCb);
});
});
});
Example #26
Source File: lookupExposedFunctions.test.js From ClusterAnalysis with BSD 3-Clause "New" or "Revised" License | 5 votes |
describe('c-lookup exposed functions', () => {
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);
}
});
it('getSelection returns correct selection when initial selection is an array', () => {
// Create element
const element = createElement('c-lookup', {
is: Lookup
});
element.selection = SAMPLE_SEARCH_ITEMS;
// Verify selection
const selection = element.getSelection();
expect(selection.length).toBe(2);
});
it('getSelection returns correct selection when initial selection is a single item', () => {
// Create element
const element = createElement('c-lookup', {
is: Lookup
});
element.selection = SAMPLE_SEARCH_ITEMS[0];
// Verify selection
const selection = element.getSelection();
expect(selection.length).toBe(1);
});
it('setSearchResults renders correct results', () => {
// Create element
const element = createElement('c-lookup', {
is: Lookup
});
element.setSearchResults(SAMPLE_SEARCH_ITEMS);
document.body.appendChild(element);
// Query for rendered list items
const listItemEls = element.shadowRoot.querySelectorAll('li');
expect(listItemEls.length).toBe(2);
const resultItemEls = listItemEls[0].querySelectorAll('lightning-formatted-rich-text');
expect(resultItemEls.length).toBe(2);
});
});
Example #27
Source File: classLookupOption.test.js From Schedul-o-matic-9000 with BSD 3-Clause "New" or "Revised" License | 4 votes |
describe("c-class-lookup-option", () => {
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);
}
});
it("shows class name and appropriate icon based on public property", () => {
const element = createElement("c-class-lookup-option", {
is: ClassLookupOption
});
element.item = ITEM;
document.body.appendChild(element);
const iconEl = element.shadowRoot.querySelector("lightning-icon");
expect(iconEl.iconName).toBe("utility:clock");
expect(iconEl.alternativeText).toBe("Schedulable");
const spanEl = element.shadowRoot.querySelector(".apexClassName");
expect(spanEl.title).toBe(ITEM.label);
expect(spanEl.textContent).toBe(ITEM.label);
const markEl = element.shadowRoot.querySelector("mark");
expect(markEl.textContent).toBe(ITEM.mark);
const divEl = element.shadowRoot.querySelector("div");
expect(divEl.classList).not.toContain("slds-has-focus");
expect(divEl.ariaSelected).toBe("false");
});
it("fires optionselected event when clicked", async () => {
const mockOptionSelectedHandler = jest.fn();
const element = createElement("c-class-lookup-option", {
is: ClassLookupOption
});
element.item = ITEM;
element.addEventListener("optionselected", mockOptionSelectedHandler);
document.body.appendChild(element);
const divEl = element.shadowRoot.querySelector("div");
divEl.click();
expect(mockOptionSelectedHandler).toHaveBeenCalledTimes(1);
const optionSelectedEvent = mockOptionSelectedHandler.mock.calls[0][0];
expect(optionSelectedEvent.detail).toBe(ITEM.value);
});
it("activates/deactivates on mouse enter/leave", async () => {
const mockOptionActivatedHandler = jest.fn();
const element = createElement("c-class-lookup-option", {
is: ClassLookupOption
});
element.item = ITEM;
element.addEventListener("optionactivated", mockOptionActivatedHandler);
document.body.appendChild(element);
const divEl = element.shadowRoot.querySelector("div");
divEl.dispatchEvent(new Event("mouseenter"));
expect(mockOptionActivatedHandler).toHaveBeenCalledTimes(1);
const optionActivatedEvent = mockOptionActivatedHandler.mock.calls[0][0];
expect(optionActivatedEvent.detail).toBe(ITEM.value);
await Promise.resolve();
expect(divEl.classList).toContain("slds-has-focus");
expect(divEl.ariaSelected).toBe("true");
divEl.dispatchEvent(new Event("mouseleave"));
await Promise.resolve();
expect(divEl.classList).not.toContain("slds-has-focus");
expect(divEl.ariaSelected).toBe("false");
});
it("shows focused option and activated aria if active option matches item", () => {
const element = createElement("c-class-lookup-option", {
is: ClassLookupOption
});
element.item = ITEM;
element.activeOption = ACTIVE_OPTION;
document.body.appendChild(element);
const divEl = element.shadowRoot.querySelector("div");
expect(divEl.classList).toContain("slds-has-focus");
expect(divEl.ariaSelected).toBe("true");
});
});
Example #28
Source File: tableauViz.test.js From tableau-viz-lwc with MIT License | 4 votes |
describe('tableau-viz', () => {
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);
}
// Clear mocks so that every test run has a clean implementation
jest.clearAllMocks();
// Reset globals
global.tableauMockInstances = [];
});
// Helper function to wait until the microtask queue is empty. This is needed for promise
// timing when the platformResourceLoader promises.
function flushPromises() {
// eslint-disable-next-line no-undef
return new Promise((resolve) => setImmediate(resolve));
}
it('loads the Tableau JS API static resource', () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = VIZ_URL;
document.body.appendChild(element);
// Validation that the loadScript promise is called once.
expect(loadScript.mock.calls.length).toBe(1);
// Validation that the tableau JS API static resource is passed as parameter.
expect(loadScript.mock.calls[0][1]).toEqual(TABLEAU_JS_API);
});
it('passes the right options to the Tableau JS API', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = VIZ_URL;
element.showTabs = true;
element.showToolbar = false;
element.height = 650;
document.body.appendChild(element);
await flushPromises();
expect(global.tableauMockInstances.length).toBe(1);
const instance = global.tableauMockInstances[0];
expect(instance.options.hideTabs).toBeFalsy();
expect(instance.options.hideToolbar).toBeTruthy();
expect(instance.options.height).toBe('650px');
});
it('calls the right viz URL without filters', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.height = '550';
element.vizUrl = VIZ_URL_NO_FILTERS;
document.body.appendChild(element);
await flushPromises();
const vizPlaceholder = element.shadowRoot.querySelector(
'div.tabVizPlaceholder'
);
expect(vizPlaceholder).not.toBeNull();
expect(global.tableauMockInstances.length).toBe(1);
const instance = global.tableauMockInstances[0];
expect(instance.vizToLoad).toBe(
VIZ_DISPLAY + vizPlaceholder.offsetWidth + '%2C550'
);
});
it('calls the right viz URL without filters on RecordPage', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = VIZ_URL;
element.filterOnRecordId = false;
element.height = '550';
element.objectApiName = 'Account';
element.recordId = 'mockId';
document.body.appendChild(element);
await flushPromises();
const div = element.shadowRoot.querySelector('div.tabVizPlaceholder');
expect(div).not.toBeNull();
expect(global.tableauMockInstances.length).toBe(1);
const instance = global.tableauMockInstances[0];
expect(instance.vizToLoad).toBe(
VIZ_DISPLAY + div.offsetWidth + '%2C550'
);
});
it('calls the right viz URL with record id filter', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = VIZ_URL;
element.filterOnRecordId = true;
element.height = '550';
element.objectApiName = 'Account';
element.recordId = 'mockId';
document.body.appendChild(element);
await flushPromises();
const vizPlaceholder = element.shadowRoot.querySelector(
'div.tabVizPlaceholder'
);
expect(vizPlaceholder).not.toBeNull();
expect(global.tableauMockInstances.length).toBe(1);
const instance = global.tableauMockInstances[0];
expect(instance.vizToLoad).toBe(
`${VIZ_DISPLAY}${vizPlaceholder.offsetWidth}%2C550&Account+ID=mockId`
);
});
it('calls the right viz URL with advanced filters', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = VIZ_URL;
element.filterOnRecordId = false;
element.height = 650;
element.objectApiName = 'Account';
element.recordId = 'mockId';
element.sfAdvancedFilter = 'Account.Name';
element.tabAdvancedFilter = 'Name';
document.body.appendChild(element);
getRecord.emit(mockGetRecord);
await flushPromises();
const vizPlaceholder = element.shadowRoot.querySelector(
'div.tabVizPlaceholder'
);
expect(vizPlaceholder).not.toBeNull();
expect(global.tableauMockInstances.length).toBe(1);
const instance = global.tableauMockInstances[0];
expect(instance.vizToLoad).toBe(
`${VIZ_DISPLAY}${vizPlaceholder.offsetWidth}%2C650&Name=SpacelySprockets`
);
});
it('reports error when invalid viz URL failed creating URL object', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = 'invalid';
document.body.appendChild(element);
await flushPromises();
const errorEl = element.shadowRoot.querySelector(
'h3.slds-text-color_destructive'
);
expect(errorEl).not.toBeNull();
expect(errorEl.textContent).toBe('Invalid URL: invalid');
expect(global.tableauMockInstances.length).toBe(0);
});
it('reports error when invalid javascript viz URL', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
// eslint-disable-next-line no-script-url
element.vizUrl = 'javascript:void(0)';
document.body.appendChild(element);
await flushPromises();
const errorEl = element.shadowRoot.querySelector(
'h3.slds-text-color_destructive'
);
expect(errorEl).not.toBeNull();
expect(errorEl.textContent).toBe(
'Invalid URL. Make sure the link to the Tableau view is using HTTPS.'
);
expect(global.tableauMockInstances.length).toBe(0);
});
it('reports error when invalid viz URL is HTTP', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = 'http://fakeurl.com';
document.body.appendChild(element);
await flushPromises();
const errorEl = element.shadowRoot.querySelector(
'h3.slds-text-color_destructive'
);
expect(errorEl).not.toBeNull();
expect(errorEl.textContent).toBe(
'Invalid URL. Make sure the link to the Tableau view is using HTTPS.'
);
expect(global.tableauMockInstances.length).toBe(0);
});
it('reports error when invalid viz URL contains # right after the hostname', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl =
'https://vizurl.com/#/views/WorldIndicators/Population';
document.body.appendChild(element);
await flushPromises();
const errorEl = element.shadowRoot.querySelector(
'h3.slds-text-color_destructive'
);
expect(errorEl).not.toBeNull();
expect(errorEl.textContent).toBe(
"Invalid URL. Enter the link for a Tableau view. Click Copy Link to copy the URL from the Share View dialog box in Tableau. The link for the Tableau view must not include a '#' after the name of the server."
);
expect(global.tableauMockInstances.length).toBe(0);
});
it('reports error when advanced filter and missing Salesforce field', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = VIZ_URL;
element.tabAdvancedFilter = 'mockValue';
document.body.appendChild(element);
await flushPromises();
const errorEl = element.shadowRoot.querySelector(
'h3.slds-text-color_destructive'
);
expect(errorEl).not.toBeNull();
expect(errorEl.textContent).toBe(
'Advanced filtering requires that you select both Tableau and Salesforce fields. The fields should represent corresponding data, for example, user or account identifiers.'
);
expect(global.tableauMockInstances.length).toBe(0);
});
it('reports error when advanced filter and missing Tableau field', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = VIZ_URL;
element.sfAdvancedFilter = 'mockValue';
document.body.appendChild(element);
await flushPromises();
const errorEl = element.shadowRoot.querySelector(
'h3.slds-text-color_destructive'
);
expect(errorEl).not.toBeNull();
expect(errorEl.textContent).toBe(
'Advanced filtering requires that you select both Tableau and Salesforce fields. The fields should represent corresponding data, for example, user or account identifiers.'
);
expect(global.tableauMockInstances.length).toBe(0);
});
it('reports error when advanced filter and getRecord fails', async () => {
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = VIZ_URL;
element.sfAdvancedFilter = 'mockValue';
element.tabAdvancedFilter = 'Name';
document.body.appendChild(element);
getRecord.error();
await flushPromises();
const errorEl = element.shadowRoot.querySelector(
'h3.slds-text-color_destructive'
);
expect(errorEl).not.toBeNull();
expect(errorEl.textContent).toMatch(/Failed to retrieve record data/);
expect(global.tableauMockInstances.length).toBe(0);
});
it('reports error when advanced filter and field value is missing', async () => {
const MISSING_FIELD = 'Account.MissingField';
const element = createElement('c-tableau-viz', {
is: TableauViz
});
element.vizUrl = VIZ_URL;
element.objectApiName = 'Account';
element.recordId = 'mockId';
element.sfAdvancedFilter = MISSING_FIELD;
element.tabAdvancedFilter = 'Name';
document.body.appendChild(element);
getRecord.emit(mockGetRecord);
await flushPromises();
const errorEl = element.shadowRoot.querySelector(
'h3.slds-text-color_destructive'
);
expect(errorEl).not.toBeNull();
expect(errorEl.textContent).toBe(
`Failed to retrieve value for field ${MISSING_FIELD}`
);
expect(global.tableauMockInstances.length).toBe(0);
});
describe('Test mobile detection', () => {
it('Detects that this is mobile', () => {
const appendFn = jest.fn();
const vizToLoad = {
searchParams: {
append: appendFn
}
};
const device = 'iPhone';
const id = '9456F6A5-A240-4653-948C-0AC79890275E';
const userAgent = `SalesforceMobileSDK/7.1.2 iOS/13.6 (${device}) Chatter/226.030(6201285) Hybrid uid_${id}`;
TableauViz.checkForMobileApp(vizToLoad, userAgent);
expect(appendFn.mock.calls.length).toBe(4);
expect(appendFn.mock.calls[0][0]).toBe(':use_rt');
expect(appendFn.mock.calls[0][1]).toBe('y');
expect(appendFn.mock.calls[1][0]).toBe(':client_id');
expect(appendFn.mock.calls[1][1]).toBe('TableauVizLWC');
expect(appendFn.mock.calls[2][0]).toBe(':device_id');
expect(appendFn.mock.calls[2][1]).toBe(id);
expect(appendFn.mock.calls[3][0]).toBe(':device_name');
expect(appendFn.mock.calls[3][1]).toBe(`SFMobileApp_${device}`);
});
it('Detects that this is not mobile', () => {
const appendFn = jest.fn();
const vizToLoad = {
searchParams: {
append: appendFn
}
};
const userAgent = `Some random browser that doesn't use the SDK`;
TableauViz.checkForMobileApp(vizToLoad, userAgent);
expect(appendFn.mock.calls.length).toBe(0);
});
it('Detects that this is an Android', () => {
const appendFn = jest.fn();
const vizToLoad = {
searchParams: {
append: appendFn
}
};
const device = 'Android';
const id = '9456F6A50AC79890275E';
const userAgent = `SalesforceMobileSDK/7.1.2 (${device}) Chatter/226.030(6201285) Hybrid uid_${id}`;
TableauViz.checkForMobileApp(vizToLoad, userAgent);
expect(appendFn.mock.calls.length).toBe(4);
expect(appendFn.mock.calls[0][0]).toBe(':use_rt');
expect(appendFn.mock.calls[0][1]).toBe('y');
expect(appendFn.mock.calls[1][0]).toBe(':client_id');
expect(appendFn.mock.calls[1][1]).toBe('TableauVizLWC');
expect(appendFn.mock.calls[2][0]).toBe(':device_id');
expect(appendFn.mock.calls[2][1]).toBe(id);
expect(appendFn.mock.calls[3][0]).toBe(':device_name');
expect(appendFn.mock.calls[3][1]).toBe(`SFMobileApp_${device}`);
});
it('Generates an ID if none are in the user agent string', () => {
const appendFn = jest.fn();
const vizToLoad = {
searchParams: {
append: appendFn
}
};
const randomID = '1234';
const randomIDGenerator = jest.fn();
TableauViz.generateRandomDeviceId = randomIDGenerator;
randomIDGenerator.mockReturnValueOnce(randomID);
const device = 'Android';
const userAgent = `SalesforceMobileSDK/7.1.2 (${device}) Chatter/226.030(6201285) Hybrid`;
TableauViz.checkForMobileApp(vizToLoad, userAgent);
expect(appendFn.mock.calls.length).toBe(4);
expect(randomIDGenerator.mock.calls.length).toBe(1);
expect(appendFn.mock.calls[0][0]).toBe(':use_rt');
expect(appendFn.mock.calls[0][1]).toBe('y');
expect(appendFn.mock.calls[1][0]).toBe(':client_id');
expect(appendFn.mock.calls[1][1]).toBe('TableauVizLWC');
expect(appendFn.mock.calls[2][0]).toBe(':device_id');
expect(appendFn.mock.calls[2][1]).toBe(randomID);
expect(appendFn.mock.calls[3][0]).toBe(':device_name');
expect(appendFn.mock.calls[3][1]).toBe(`SFMobileApp_${device}`);
});
});
describe('Validate normalization functions', () => {
it('Checks Boolean normalize', () => {
let result;
result = TableauViz.booleanNormalize(true);
expect(result).toBe(true);
result = TableauViz.booleanNormalize(false);
expect(result).toBe(false);
result = TableauViz.booleanNormalize('false');
expect(result).toBe(false);
result = TableauViz.booleanNormalize('true');
expect(result).toBe(true);
});
});
});
Example #29
Source File: objectDetails.test.js From AppRecordDetails with BSD 3-Clause "New" or "Revised" License | 4 votes |
describe("c-object-details", () => {
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);
}
// Prevent data saved on mocks from leaking between tests
jest.clearAllMocks();
});
describe("verify section names and click on edit", () => {
it("getObjectDetailConfigMethod @wire data", () => {
const RECORD_ID_INPUT = '0012x000004KwDqAAK';
const OBJECT_API_NAME_INPUT = 'ACCOUNT';
const USER_ID = '005000000000000000';
const PROFILE_NAME = 'System Administrator';
const WIRE_PARAMETER = { configName: "xyz", recordId: USER_ID, fields: [PROFILE_NAME], profileNames: "System Administrator" };
// Create element
var element = createElement("c-object-details", {
is: appSpecificLayout,
});
element.profileNames = 'System Administrator';
element.recordId = RECORD_ID_INPUT;
element.objName = OBJECT_API_NAME_INPUT;
element.USER_ID = USER_ID;
element.PROFILE_NAME = PROFILE_NAME;
document.body.appendChild(element);
const recordViewForm = element.shadowRoot.querySelector('lightning-record-view-form');
expect(recordViewForm.recordId).toBe(RECORD_ID_INPUT);
expect(recordViewForm.objectApiName).toBe(OBJECT_API_NAME_INPUT);
// Emit data from @wire
getRecordAdapter.emit(mockGetRecord);
getMetadataInfoAdapter.emit(mockGetMetadataValues);
return Promise.resolve().then(() => {
try {
recordViewForm.dispatchEvent(new CustomEvent('load'));
//verify section names
const sectionNamesTags = element.shadowRoot.querySelectorAll('span');
var secNames = [];
sectionNamesTags.forEach(secNameElement => {
secNames.push(secNameElement.innerHTML);
});
sectionNamesTags[0].click();
sectionNamesTags[0].click();
const sectionNamesH3Tags = element.shadowRoot.querySelector('h3');
sectionNamesH3Tags.click();
sectionNamesH3Tags.click();
mockGetMetadataValues.data.forEach(mockElement => {
expect(secNames.includes(mockElement.secName)).toBe(true);
});
//verify the click on edit icon
const editIcons = element.shadowRoot.querySelector('.editIcon');
editIcons.click();
return Promise.resolve().then(() => {
//record edit form starts from here
const recordEditForm = element.shadowRoot.querySelector('lightning-record-edit-form');
//mock scroll to view functinality
let scrollIntoViewMock = jest.fn();
window.HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;
recordEditForm.dispatchEvent(new CustomEvent('load'));
expect(scrollIntoViewMock).toBeCalled();
expect(recordEditForm.recordId).toBe(RECORD_ID_INPUT);
expect(recordEditForm.objectApiName).toBe(OBJECT_API_NAME_INPUT);
// Validate if save and cancel buttons are defined
const buttonLabels = ['Cancel', 'Save'];
const buttonElements = element.shadowRoot.querySelectorAll('lightning-button button');
buttonElements.forEach(buttonEl => {
expect(buttonLabels.includes(buttonEl.label)).toBe(true);
});
recordEditForm.dispatchEvent(new CustomEvent('success'));
const configBtn = element.shadowRoot.querySelector('lightning-button-icon');
configBtn.click();
});
} catch (e) {
console.log('--e--' + e);
}
});
});
it("getObjectDetailConfigMethod error scenario @wire data", () => {
const RECORD_ID_INPUT = '0012x000004KwDqAAK';
const OBJECT_API_NAME_INPUT = 'ACCOUNT';
const USER_ID = '005000000000000000';
const PROFILE_NAME = 'System Administrator';
const WIRE_PARAMETER = { configName: "xyz", recordId: USER_ID, fields: [PROFILE_NAME], profileNames: "System Administrator" };
// Create element
var element = createElement("c-object-details", {
is: appSpecificLayout,
});
element.profileNames = 'System Administrator';
element.recordId = RECORD_ID_INPUT;
element.objName = OBJECT_API_NAME_INPUT;
element.USER_ID = USER_ID;
element.PROFILE_NAME = PROFILE_NAME;
document.body.appendChild(element);
const recordViewForm = element.shadowRoot.querySelector('lightning-record-view-form');
// Emit data from @wire
getRecordAdapter.emit(mockGetRecord);
getMetadataInfoAdapter.emit(mockGetMetadataErrorValues);
return Promise.resolve().then(() => {
});
});
});
});