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?
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!
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.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With