Skip to content

Instantly share code, notes, and snippets.

@lakeishaaaa
Last active November 8, 2022 12:49
Show Gist options
  • Save lakeishaaaa/6f43c36de0e4387278927860cde9c0a1 to your computer and use it in GitHub Desktop.
Save lakeishaaaa/6f43c36de0e4387278927860cde9c0a1 to your computer and use it in GitHub Desktop.
Salesforce Trailhead - Lightning Web Components Tests - Write a Jest Test
import { sum } from '../sum';
describe('sum()', () => {
it('should add 1 and 2 returning 3', () => {
expect(sum(1, 2)).toBe(3);
});
});
<template>
<lightning-card title="Unit Status" icon-name="standard:bot">
<lightning-input
label="Unit Number"
value={unitNumber}
onchange={handleChange} >
</lightning-input>
<div class="slds-m-around_medium">
Unit {unitNumber} alive!
</div>
</lightning-card>
</template>
import { LightningElement, api } from 'lwc';
import { sum } from './sum';
export default class UnitTest extends LightningElement {
@api unitNumber = sum(2,3);
handleChange(event) {
this.unitNumber = event.target.value;
}
}
import { createElement } from 'lwc';
import UnitTest from 'c/unitTest';
describe('c-unit-test', () => {
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('displays unit status with default unitNumber', () => {
const element = createElement('c-unit-test', {
is: UnitTest
});
expect(element.unitNumber).toBe(5);
// Add the element to the jsdom instance
document.body.appendChild(element);
// Verify displayed greeting
const div = element.shadowRoot.querySelector('div');
expect(div.textContent).toBe('Unit 5 alive!');
});
it('displays unit status with updated unitNumber', () => {
const element = createElement('c-unit-test', {
is: UnitTest
});
// Add the element to the jsdom instance
document.body.appendChild(element);
// Update unitNumber after element is appended
element.unitNumber = 6
const div = element.shadowRoot.querySelector('div');
// Verify displayed unit status
expect(div.textContent).not.toBe('Unit 6 alive!');
// 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(() => {
expect(div.textContent).toBe('Unit 6 alive!');
});
});
it('displays unit status with input change event', () => {
const element = createElement('c-unit-test', {
is: UnitTest
});
document.body.appendChild(element);
const div = element.shadowRoot.querySelector('div');
// Trigger unit status input change
const inputElement = element.shadowRoot.querySelector('lightning-input');
inputElement.value = 7;
inputElement.dispatchEvent(new CustomEvent('change'));
return Promise.resolve().then(() => {
expect(div.textContent).toBe('Unit 7 alive!');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment