javascript - How to spy on individual functions that are default exports
问题描述
I am trying to spy on a function that is used by the function I am actually testing, so the structure is a bit like this:
const trueOrFalse = (args) => {
return true // or false;
}
export default TrueOrFalse;
and the function I want to import it into does
import trueOrFalse from './trueOrFalse';
const myFunc = () => {
const successful = trueOrFalse();
if (!successful) return;
// Otherwise do something else
}
For my test now I need my trueOrFalse()
to always return false
for example. If this was exported differently I'd be able to use jest.spyOn
like this:
jest.spyOn(utils, 'trueOrFalse').mockImplementation(() => false);
But with this being a default export I can't do this, can I?
jest.spyOn(???, 'trueOrFalse').mockImplementation(() => false);
How can I spy on or mock this dependent function?
解决方案
可以在模块对象上监视或模拟函数:
import * as trueOrFalseMod from './trueOrFalse';
...
jest.spyOn(trueOrFalseMod, 'default');
这是因为 ES 导入总是在内部导入后引用对象属性。如果模块对象根据 ES 模块规范是只读的,这可能不起作用,这取决于特定的 Jest 设置。
否则需要模拟一个模块:
import trueOrFalse from './trueOrFalse';
jest.mock('./trueOrFalse');
这应该导致trueOrFalse
成为可以根据测试更改实现的存根:
trueOrFalse.mockReturnValue(false);
推荐阅读
- npm - 用用户身份验证令牌覆盖 npm 项目身份验证令牌?
- r - 用 N/A 替换每列中的多个行值
- c++ - 如何将 libcurl 构建为静态库并在项目中使用?
- c# - 如何加快将大型 csv 文件导入 mysql 数据库的速度?
- python - 将生成器表达式传递给 any() 和 all()
- python - 如何处理 Spark 中的架构更改?
- python - 如何在opencv中将相机切换为YUY2格式
- orchardcms - 如何从 Orchard 的后台任务中更新 ContentItem?
- javascript - 如何在 Node.js 中追加到缓冲区
- html - 当浏览器窗口宽度小于 400 像素时,正文宽度不是 100%