如何使用jest框架测试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');
}
}
Run Code Online (Sandbox Code Playgroud)
我们如何测试这种类型的功能?
小智 16
测试 void 函数的最佳方法是模拟其依赖项的行为。
// module being tested
import sideEffect from 'some-module';
export default function () {
sideEffect();
}
Run Code Online (Sandbox Code Playgroud)
使用文件模拟和函数期望,您可以断言该函数按预期调用了另一个模块:
import hasSideEffect from './hasSideEffect';
import sideEffect from 'some-module';
jest.mock('some-module');
test('calls sideEffect', () => {
hasSideEffect();
expect(sideEffect).toHaveBeenCalledTimes(1);
expect(sideEffect).toHaveBeenCalledWith();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3642 次 |
| 最近记录: |