如何解决开玩笑的测试函数,在其中定义变量
我想在.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的完整上下文,以便一起测试这两个功能。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。