问题描述
我想在.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的完整上下文,以便一起测试这两个功能。