TDD LWC with Jest in Salesforce

Ben Butler
2 min readOct 7, 2021

--

There is a basic practice in test driven development. Red, Green, Refactor.

Red: start writing a test until it fails

Green: write the solution up until the test doesn’t fail

Refactor: refactor the code to keep it clean

Bob Martin explained three rules for TDD

Write production code only to pass a failing unit test.

Write no more of a unit test than sufficient to fail (compilation failures are failures).

Write no more production code than necessary to pass the one failing unit test.

This is my journey to use TDD using Jest with LWC against the push of a custom stack that takes even numbers but not odd numbers.

To start, I created a test until it ran into an error: “TypeError: (0 , _cstack.push) is not a function”

//test
import { push } from '../cstack';

describe('push(even)', () => {
it('pushing an even number should add to the stack', () => {
expect(push(2));
});
});

Then I create the stack until the error went away

//custom stack
export function push(value) {}

Then I update the test until I received another error:

Expected: ArrayContaining [2]
Received: undefined

//test
import { push } from '../cstack';
describe('push(even)', () => {
it('pushing an even number should add to the stack', () => {
expect(push(2)).toEqual(expect.arrayContaining([2]));
});
});

Then I update the stack to fix the test

//custom stack
let stack = [];
export function push(value) {
stack.push(value);
return stack;
}

The stack customization is to disallow odd numbers, so I will create a test to verify that until it fails.

//test
import { push } from '../cstack';
describe('push(even)', () => {
it('pushing an even number should add to the stack', () => {
expect(push(2)).toEqual(expect.arrayContaining([2]));
});
});
describe('push(even)', () => {
it('pushing an even number should add to the stack', () => {
expect(push(1)).toEqual(expect.not.arrayContaining([1]));
});
});

Then I update the logic of the stack until the new test passes

//custom stack
let stack = [];
export function push(value) {
if (value % 2 == 0)
stack.push(value);
return stack;
}

We now have a successful functionality using TDD.

This doesn’t include tests relating to the GUI on purpose. According to Bob Martin, testing the GUI, it isn’t worth it. Effective testing requires us to decouple the business rules from the user interface. It adds needless fragility. That means we probably do not want tests to have something that looks like this in it:

document.body.appendChild(element);
element.unitNumber = 6
const div = element.shadowRoot.querySelector('div');

--

--