Jest test functions that define variables in it

2.5k Views Asked by At

I want to write some Jest tests for JavaScript functions in a .mjs file. Within these functions, variables are defined by calling other functions. For example:

export function getCurrentVideo() {
     var currentVideo = VideoList.GetCurrentVideo()
    console.log(currentVideo);
    return "This is the video:" + currentVideo
}

In this case I will receive undefined, right? Because VideoList.GetCurrentVideo can't be reached.

Test will be something like:

const  getCurrentVideo  = import('../').getCurrentVideo;

describe('getCurrentVideo', () => {
    test('if getCurrentVideo will return "This is the video:" + currentVideo', () => {
        expect(getCurrentVideo).toBe('This is the video:" + currentVideo');
    });
});

I know you can add parameters to the function, but that will mean that I have to re-write the functions just for test purposes. It isn't my code, it's a huge project where the owner wants some tests for it.

1

There are 1 best solutions below

6
On

You can mock function, assuming they work correctly (and test them separately):

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);
    });
});

Or you can provide a full context of VideoList, so that the two function are tested together.