开玩笑的测试函数,在其中定义变量

问题描述

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...