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?
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();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.