【问题标题】:How to unit test TweenMax? Potential mock?如何对 TweenMax 进行单元测试?潜在的模拟?
【发布时间】:2019-03-19 17:35:50
【问题描述】:

我正在尝试对使用 GSAP 中的 TweenMax 的函数进行单元测试,但我不确定如何最好地进行...

@ViewChild('dropdown') dropdown: ElementRef;
expanded = false;

toggleDropdown() {
    const dropdown = this.dropdown.nativeElement;

    TweenMax.to(dropdown, 0.5, {
      css: {
        height: this.expanded ? '34px' : '376px'
      },
      ease: Power2.easeInOut,
    });

    this.expanded = !this.expanded;
  }

我正在考虑可能会嘲笑 TweenMax,但我所做的尝试收到了错误:

本应是间谍,但得到了 Object({ to: spy on unknown.to })。

beforeEach(async(() => {
    mockTween = createSpyObj(['to']);

    TestBed.configureTestingModule({
      imports: [...],
      declarations: [...],
      providers: [... ,
        {provide: TweenMax, useValue: mockTween}
      ]
    });

    ...
  }));

it('should set dropdown height to 376px if not currently expanded', () => {
    component.expanded = false;

    component.toggleDropdown();

    expect(mockTween).toHaveBeenCalled();
  });

【问题讨论】:

    标签: javascript angular typescript unit-testing testing


    【解决方案1】:

    对不起,我删除了我之前的答案,因为它越来越长。

    根据您提供的 stackblitz,我自己也创建了一个:

    https://stackblitz.com/edit/angular-6-jasmine-tween-j5wsz9?file=app/tween/tween.component.spec.ts

    如您所见,它就像一个魅力。

    fdescribe('TweenComponent', () => {
      let fixture: ComponentFixture<TweenComponent>, component: TweenComponent;
      beforeEach(() => {
        TestBed.configureTestingModule({
          declarations: [TweenComponent]
        }).compileComponents();
    
        fixture = TestBed.createComponent(TweenComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should call Tween.to', () => {
        spyOn(TweenMax, 'to');
        component.toggleDropdown();
        expect(TweenMax.to).toHaveBeenCalled();
      });
    });
    

    【讨论】:

    • 如果您可以重现该问题,请随时编辑此闪电战,否则问题出在您的代码中!
    • 什么?!我实际上只是复制了it 的样式,它有效吗?!我们之前尝试创建 spyObj 的方式一定有问题?
    • 你知道我可以检查实际 CSS 值是否已更改的方法吗?我所做的一切也都是失败的。在这种情况下,我会写:expect(component.myElement.nativeElement.style.height).toBe('50px');
    • 那么您需要使用spyOn(TweenMax, 'to').and.callThrough();,否则该函数不会被调用(由间谍代替)。另外,如果测试仍然失败,请考虑使用fixture.detectChanges();
    • 但是,正如我们在其他主题中已经讨论过的那样,您应该期望您的函数已经使用给定的参数调用,而不是检查函数是否有效:通过这样做,您抽象了一个依赖项,使您的单元测试成为真正的单元测试(而不是依赖于第二个单元的单元测试)
    猜你喜欢
    • 2019-08-22
    • 2018-04-04
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多