Jest的null的getReversedNavigationSections

时间:2019-05-29 14:27:19

标签: javascript jestjs enzyme

我在滚动时有这样的手柄:

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

1 个答案:

答案 0 :(得分:1)

首先,您是否尝试过调试此测试?

您收到该错误的事实意味着这里有问题。

document.getElementById(navigationSections[i].id)

这意味着您根本不了解元素。

没有看到其余的实现,我最初的猜测是,您正在将Virtual DOM操作与直接DOM操作拼接在一起,并且有些东西迷失了,但是我无法根据代码片段确定。