需要为scrollIntoView函数调用提供Angular jasmine测试案例。

问题描述 投票:0回答:1

这是我想测试的方法,但不明白如何模拟滚动查看,有没有什么文档可以帮助我理解jasmine测试,我收到错误信息说ele.scrollIntoView不是一个函数。

scrollIntoViewMethod(): void {
    const offsetTopDiv = '.highlight';
    const ele = this.el.nativeElement.querySelector(`${offsetTopDiv}`);
    ele.scrollIntoView({
      behavior: 'smooth',
      block: 'center',
      inline: 'nearest',
    });
  }
angular unit-testing jasmine karma-jasmine
1个回答
1
投票

根据我的理解 el 是一个 ViewChild,然后你可以嘲笑它 querySelector.

it('test', () => {
  // assuming that env is set and ready
  fixture.detectChanges();

  // adding spy
  const querySelectorSpy = spyOn(component.el.nativeElement, 'querySelector');

  // creating a stub
  const eleSpy = {
    scrollIntoView: jasmine.crateSpy('eleSpy.scrollIntoView'),
  };

  // setting the return value
  querySelectorSpy.and.returnValue(eleSpy);

  // action
  component.scrollIntoViewMethod();

  // assertion
  expect(querySelectorSpy).toHaveBeenCalledWith('.highlight');
  expect(eleSpy.scrollIntoView).toHaveBeenCalledWith({
    behavior: 'smooth',
    block: 'center',
    inline: 'nearest',
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.