首页 > 解决方案 > 在其中定义变量的 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');
    });
});

我知道您可以向函数添加参数,但这意味着我必须重新编写函数以用于测试目的。这不是我的代码,它是一个巨大的项目,所有者想要对其进行一些测试。

标签: javascripttestingjestjsmjs

解决方案


您可以模拟函数,假设它们正常工作(并单独测试它们):

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 上下文,以便将两个函数一起测试。


推荐阅读