如何使用开玩笑测试void JavaScript函数



如何使用开玩笑的框架测试void javascript函数(一个不返回任何内容的函数(?您能提供相同的例子吗?

/**
 * 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');
    }
}

我们如何测试这种功能?

测试void函数的最佳方法是模拟其依赖性的行为。

// module being tested
import sideEffect from 'some-module';
export default function () {
    sideEffect();
}

使用文件模拟和函数期望,您可以断言该函数称为其他模块:

import hasSideEffect from './hasSideEffect';
import sideEffect from 'some-module';
jest.mock('some-module');
test('calls sideEffect', () => {
    hasSideEffect();
    expect(sideEffect).toHaveBeenCalledTimes(1);
    expect(sideEffect).toHaveBeenCalledWith();
});

最新更新