【问题标题】:Test if class is changed with Jasmine and Karma测试是否使用 Jasmine 和 Karma 更改类
【发布时间】:2020-03-27 01:44:36
【问题描述】:

我正在尝试通过以下方式测试按钮是否被点击:

单击按钮时,某些元素类从wrapper-container 更改为wrapper-container-expanded(我不想检查单击按钮时是否调用了该函数-这不是我的目的)。

我正在尝试通过以下方式检查:

it('should class be changed', ()=>{ 
   fixture.detectChanges()
   clickedElement.nativeElement.click() // click the button that causes the class change
   elementToBeExpanded = fixture.debugElement.nativeElement.querySelector('wrapper-container-expanded')
   expext(elementToBeExpanded).toBeTruthy() // check if the element with the new class exists in the DOM -the elementToBeExpanded is null
})

虽然我可以看到调用了函数并更改了类,但找不到具有新类的元素并且旧的wrapper-container似乎存在。

【问题讨论】:

标签: angular unit-testing jasmine karma-jasmine angular-unit-test


【解决方案1】:

点击事件后需要调用fixture.detectChanges()

it('should class be changed', () => { 
   // ...
   clickedElement.nativeElement.click() // click the button that causes the class change
   fixture.detectChanges()              // detect the changes!!
   // ...
})

【讨论】:

  • 当我添加 spyOn(component, 'the function that casuses the change class') 测试中断..任何线索?
  • 我自己想通了,spyOn 创建了该方法的模拟,直到我添加了 .and.callThrough()..
  • 太好了,你找到了!是的,确实,如果你在某个方法上安装了一个间谍并希望调用真正的方法,你需要and.callThrough
猜你喜欢
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
相关资源
最近更新 更多