簡體   English   中英

內置 Javascript 函數的模擬結果

[英]Mock results of built-in Javascript functions

我正在為定義為的函數 xyz 編寫測試:

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

如何模擬encodeURIComponent( document.URL )的結果? 有沒有辦法模擬encodeURIComponent()以便 Jest 可以使用模擬而不是真實的模擬?

您可以使用jest.fn模擬encodeURIComponent實現,如下所示:

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

您想要的模擬替換函數作為參數傳遞給jest.fn ,可用於讓它返回您需要的任何值。 或者,您也可以使用jest.spyOn ,它使您能夠僅模擬一次(或保留原始實現並僅跟蹤它被調用的次數)。

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

除了提供模擬實現之外,還可以只模擬返回值,如下所示:

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

您可以在此處閱讀更多信息: Jest Mock 函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM