How to Test Void Javascript Functions Using Jest?

How to test void javascript function (a function that does not return anything) using jest framework? Can you please provide an example for the same?

/**
 * this function is used to toggle the input type password field
 * @param element {DOMElement} - field to be toggled
 */
export const togglePassword = (element) => {
    const type = element.getAttribute('type');
    if (type === 'text') {
        element.setAttribute('type', 'password');
    } else {
        element.setAttribute('type', 'text');
    }
}

How can we test such type of functions?

3

1 Answer

The best way to test a void function is by mocking the behavior of its dependencies.

// module being tested
import sideEffect from 'some-module';

export default function () {
    sideEffect();
}

Using file mocking and function expectations, you can assert that the function called the other module as expected:

import hasSideEffect from './hasSideEffect';
import sideEffect from 'some-module';

jest.mock('some-module');

test('calls sideEffect', () => {
    hasSideEffect();

    expect(sideEffect).toHaveBeenCalledTimes(1);
    expect(sideEffect).toHaveBeenCalledWith();
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest