首页 > 解决方案 > scrollIntoView 函数调用需要角茉莉花测试用例

问题描述

这是我想测试但无法理解如何模拟 scrollIntoView 的方法。是否有任何文档可以帮助我理解茉莉花测试。我收到错误消息说 ele.scrollIntoView 不是函数。

scrollIntoViewMethod(): void {
    const offsetTopDiv = '.highlight';
    const ele = this.el.nativeElement.querySelector(`${offsetTopDiv}`);
    ele.scrollIntoView({
      behavior: 'smooth',
      block: 'center',
      inline: 'nearest',
    });
  }

标签: angularunit-testingjasminekarma-jasmine

解决方案


据我了解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',
  });
});

推荐阅读