简体   繁体   English

内置 Javascript 函数的模拟结果

[英]Mock results of built-in Javascript functions

I'm writing a test for a function xyz defined as:我正在为定义为的函数 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 '';
    }   
}

How can I mock the result of encodeURIComponent( document.URL ) ?如何模拟encodeURIComponent( document.URL )的结果? Is there a way I can mock encodeURIComponent() so that Jest can use the mock instead of the real one?有没有办法模拟encodeURIComponent()以便 Jest 可以使用模拟而不是真实的模拟?

You can mock the encodeURIComponent implementation using jest.fn , like so:您可以使用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;
});

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.您想要的模拟替换函数作为参数传递给jest.fn ,可用于让它返回您需要的任何值。 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).或者,您也可以使用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');
});

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您可以在此处阅读更多信息: Jest Mock 函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM