javascript - 在其中定义变量的 Jest 测试函数
问题描述
我想在 .mjs 文件中为 JavaScript 函数编写一些 Jest 测试。在这些函数中,变量是通过调用其他函数来定义的。例如:
export function getCurrentVideo() {
var currentVideo = VideoList.GetCurrentVideo()
console.log(currentVideo);
return "This is the video:" + currentVideo
}
在这种情况下,我会收到未定义的,对吧?因为无法访问 VideoList.GetCurrentVideo。
测试将类似于:
const getCurrentVideo = import('../').getCurrentVideo;
describe('getCurrentVideo', () => {
test('if getCurrentVideo will return "This is the video:" + currentVideo', () => {
expect(getCurrentVideo).toBe('This is the video:" + currentVideo');
});
});
我知道您可以向函数添加参数,但这意味着我必须重新编写函数以用于测试目的。这不是我的代码,它是一个巨大的项目,所有者想要对其进行一些测试。
解决方案
您可以模拟函数,假设它们正常工作(并单独测试它们):
const getCurrentVideo = import('../').getCurrentVideo;
describe('getCurrentVideo', () => {
it('if getCurrentVideo will return "This is the video:" + currentVideo', () => {
const currentVideo = 'testCurrentVideo';
window.VideoList = {
GetCurrentVideo: jest.fn(() => currentVideo)
}
expect(getCurrentVideo).toBe('This is the video:' + currentVideo);
});
});
或者您可以提供完整的 VideoList 上下文,以便将两个函数一起测试。
推荐阅读
- c++ - CMake:无法打开共享对象文件:没有这样的文件或目录
- python - 为什么这两个使用 tkinter 创建小部件网格的程序执行不同?
- bash - 使用多个 if 语句生成命令所需的语法
- ruby-on-rails - Rails find_or_create_by 将强制转换添加到哈希值 json 类型属性?
- html - 量角器找不到 Angular 日期选择器
- elasticsearch - Elasticsearch top_hits 聚合与最新文档
- react-native - react-native 应用程序中某些屏幕的模态导航
- wpf - 如何从 DataGrid wpf 中的 ComboBox 列中获取 SelectedItem 属性
- excel - 从多个关闭的工作簿复制/特殊粘贴范围到主工作簿
- mysql - mysql_real_escape_string():在数据库插入中拒绝访问