簡體   English   中英

防反跳功能單元測試

[英]Debounce function unit test

我在componentDidMount內部使用了一個反跳功能,如下所示:

    ...
    if (setNavigationSections) {
        setNavigationSections(filteredFieldGroups);
        window.addEventListener('scroll', debounce(50, this.getNavigationActive));
    }  
    ...

我對此有一個單元測試:

    it('should add a scroll handler on mount', () => {
        // const d = instance.getNavigationActive;
        // const deb = debounce(50, d);
        // expect(window.addEventListener).toHaveBeenCalledWith('scroll', deb); 
        expect(window.addEventListener).toHaveBeenCalledWith('scroll', instance.getNavigationActive);
    });

單元測試失敗,消息為: 在此處輸入圖片說明

我已經嘗試了一種可能的解決方案,例如注釋代碼中的解決方案,但仍然失敗。

我是否可能需要以其他方式模擬去抖動功能?

在實際代碼中, addEventListener方法是通過scrolldebounce調用的,但是在測試時,我們試圖使用錯誤的第二個參數進行測試。 您可以使用jest.mock模擬去抖動方法,如下所示:

import { debounce } from 'throttle-debounce';
jest.mock('throttle-debounce', () => {
    return {
        debounce: jest.fn().mockReturnValue('mockDebouncedValue')
    }
})
describe('your test description', () => {
    it('should add a scroll handler on mount', () => {
        // here debounce points to the mocked function
        // since addEventListener is called with the value which is returned after calling debounce, so we check here.
        expect(window.addEventListener).toHaveBeenCalledWith('scroll','mockDebouncedValue');
        expect(debounce).toBeCalled();
    });
 });

暫無
暫無

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

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