Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 452
Swarnali Sarkar Avatar asked Apr 21 '17 06:04

Swarnali Sarkar


People also ask

Does Jest work with JavaScript?

Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!

How do you use spyOn function in Jest?

To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.

How does Jest fn () work?

The jest. fn method is, by itself, a higher-order function. It's a factory method that creates new, unused mock functions. Also, as we discussed previously, functions in JavaScript are first-class citizens.


1 Answers

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();
});
like image 200
Alex Robertson Avatar answered Sep 20 '22 13:09

Alex Robertson