Stack Exchange
Mock results of built-in Javascript functions
I'm writing a test for a function xyz defined as:
export const socialShare = function( socialType ) {

    const url  = encodeURIComponent( document.URL );
    const text = encodeURIComponent( document.title );

    switch( socialType ) {
        case 'social-mail':
            return `mailto:example@email.com?subject=${text}&body=${text}\n${url}`;

        case 'social-facebook':
            return `//www.facebook.com/sharer/sharer.php?u=${url}&t=${text}`;

        case 'social-twitter':
            return `//twitter.com/share?text=${text}&url=${url}`;

        default:
            return '';
    }   
}

How can I mock the result of encodeURIComponent( document.URL )?
Is there a way I can mock encodeURIComponent() so that Jest can use the mock instead of the real one?

Use spyOn() like spyOn('window', 'encodeURIComponent');

You can mock the encodeURIComponent implementation using jest.fn, like so:
test('Mock Encode URI component', () => {
    // Store original implementation
    const originalEncode = encodeURIComponent;

    const message = "test string ()@#$%^";
    encodeURIComponent = jest.fn(() => 'Mock Value');
    expect(yourFunction(message)).toBe('Mock Value');

    // Restore original implementation
    encodeURIComponent = originalEncode;
});

Your desired mock replacement function is passed to jest.fn as a parameter and can be used to let it return any value you need. Alternatively you can also use jest.spyOn, which provides you to ability to mock once only (or keep the original implementation and just track the number of times it is called).
test('Mock Encode URI component with Spy', () => {
    const message = "test string ()@#$%^";
    const spy = jest.spyOn(global, 'encodeURIComponent').mockImplementationOnce(() => 'Mock Value');
    expect(yourFunction(message)).toBe('Mock Value');
    expect(yourFunction(message)).toBe('test%20string%20()%40%23%24%25%5E');
});

Rather than providing a mock implemention it is also possible to just mock the return value, like so:
test('Mock Encode URI component with Spy and Return Value', () => {
    const message = "test string ()@#$%^";
    const spy = jest.spyOn(global, 'encodeURIComponent').mockReturnValueOnce('Mock Value');
    expect(yourFunction(message)).toBe('Mock Value');
});

You can read more here: Jest Mock Functions
