【问题标题】:event.stopPropagation() in Angular app leads to jasmine timing outAngular 应用程序中的 event.stopPropagation() 导致茉莉花超时
【发布时间】:2018-09-07 14:02:57
【问题描述】:

在我的 Angular 应用程序中,我有两个可点击的 div,其中一个是另一个的子级。当子div被点击时,我不希望父点击事件被触发,所以我在点击事件上使用了stopPropagation()。这是我正在做的简化版本:

<div id="parent" (click)="parentClick($event)">
  Parent
  <div id="child" (click)="childClick($event)">
    Child
  </div>
</div>

childClick 的第一行是event.stopPropagation();

这里没问题,一切都按预期进行。您可以查看the code and demo here


但是,当我尝试进行单击子 div 的茉莉花测试时,茉莉花会超时。茉莉花似乎出于某种原因冻结了。单元测试如下所示:

it(`Clicking child doesn't trigger parent`, () => {
        let childDe = fixture.debugElement.query(By.css('#child'));
        childDe.triggerEventHandler('click', { button: 0 });
        fixture.detectChanges();
        expect(component.lastClicked).toBe('child');
    });

当我运行它时,jasmine 会加载很长时间并输出以下消息: Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

如果有人知道如何在 stackblitz 中创建 jasmine 单元测试,请告诉我,我会添加它。

【问题讨论】:

    标签: javascript angular typescript jasmine angular6


    【解决方案1】:

    首先,我只是想确保您提出的错误和原因是相关的。错误 Async callback was not invoked... 通常在您为提供给 it 的函数提供 done 参数时给出:

    it('some test', (done) => { 
        ...
        done();
    });
    

    当一段时间后没有调用done 时会发生错误。但是,如果您没有 done 参数,则测试会同步运行并且不能异步超时。

    由于您提供的代码不包含done 参数,我认为此错误可能是在除此之外的测试中引起的,与事件传播无关。

    但是,如果您使用像 Protractor 这样的东西,事情可能会变得更复杂一些,但原始问题中没有提到这一点。

    【讨论】:

    • 感谢您的回答!确实,我没有提供给它的 done 论点。 Jasmine 说它是由那个测试引起的,但你是说它可能是错误的?当我删除 stopPropagation 时,它可以工作(但测试显然失败了)。我也在测试中 console.log'd,我认为它在单击时冻结了。我没有使用量角器。我现在不在工作,无法检查代码,但我会在星期一多看一下
    • 我删除了测试并且所有测试都通过了。项目中的所有测试都没有将done 参数传递给函数,因此它们都同步运行。
    【解决方案2】:

    虽然我对此并不完全满意,但我通过使用 nativeElement 而不是 debugElement 并在其上运行 click 函数使其工作,如下所示:

    it(`Clicking child doesn't trigger parent`, () => {
            let childEl = fixture.nativeElement.querySelector('#child');
            childEl.click();
            fixture.detectChanges();
            expect(component.lastClicked).toBe('child');
        });
    

    【讨论】:

      猜你喜欢
      • 2015-11-26
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多