使用 jest 启动文件下载的测试功能

Dan*_*zki 3 javascript testing unit-testing typescript jestjs

我正在尝试使用 JEST 库测试此功能(我也在项目中使用了酶),但我完全卡住了。

用几句话来描述这个功能,我用它来导出之前准备好的数据。我加工了一些数据,然后以单个字符串的形式传递它,这个 func 将它包装成一个文本文件并开始下载。

大多数情况下,它是 csv、tsv 和文本。

/**
 * Function creating text file and starting download process
 *
 * @param name - file name
 * @param extension - file extension
 * @param content - file content
 */
export const downloadTextFile = (name: string, extension: string, content: string) => {
    const link = document.createElement('a');
    link.className = 'download-helper';
    link.download = name + '.' + extension;
    link.href = `data:application/${extension},` + escape(content);
    link.click();
};
Run Code Online (Sandbox Code Playgroud)

我想养成良好的测试习惯,所以我也在尝试理解像这里这样的边缘情况。关于如何开始的任何提示?

小智 7

这个函数不是那么容易测试,因为它不返回任何值并执行副作用。对此的解决方案是使用 jest spies 来模拟该createElement函数。示例:https : //codesandbox.io/s/6xp9lqjzk3