代码之家  ›  专栏  ›  技术社区  ›  Aessandro

jest getReversedNavigationSections为空

  •  0
  • Aessandro  · 技术社区  · 5 年前

    我在卷轴上有个把手,像这样:

    handleOnScroll = () => {
        const {form, navigationSections} = this.props;
    
        const reversedSections = this.getReversedNavigationSections();
    
        const OFFSET_TOP = form === 'createIdentity' ? 34 : 140;
        const st = window.pageYOffset || document.documentElement.scrollTop; 
    
        if (st > window.lastScrollTop) {
            for (let i = 0; i < navigationSections.length; i += 1) {
                if (document.getElementById(navigationSections[i].id).getBoundingClientRect().top <= OFFSET_TOP) {
                    this.setNavigationActiveWithDebounce(navigationSections[i].id);
                }
            }
    
        } 
    
        if (st < window.lastScrollTop) {
            for (let y = 0; y < reversedSections.length; y += 1) {
                if (document.getElementById(navigationSections[y].id).getBoundingClientRect().top <= OFFSET_TOP) {
                    this.setNavigationActiveWithDebounce(navigationSections[y].id);
                }
            }
        }
    
        window.lastScrollTop = st <= 0 ? 0 : st;
    
    }
    

    像这样的测试:

        it('should handle handleOnScroll', () => {
            window.lastScrollTop = 200;
            window.pageYOffset = 50;
    
            instance.handleOnScroll();
    
            expect(instance.getReversedNavigationSections).toHaveBeenCalled();
        });
    

    我希望此测试通过(至少对于“getReversedNavigationSections”)但是我得到:

    enter image description here

    0 回复  |  直到 5 年前
        1
  •  1
  •   gibsonsp    5 年前

    首先,你试过调试这个测试吗?

    你犯了那个错误,说明这里出了问题。

    document.getElementById(navigationSections[i].id)
    

    这意味着你根本没有得到元素。

    如果看不到实现的其余部分,我最初的猜测是,您正在将虚拟dom操作与直接dom操作结合起来,有些东西在混合中丢失了,但我无法根据代码片段进行区分。

    推荐文章