【问题标题】:Spec has no expectations - Jasmine testing the callback functionSpec没有期待——Jasmine测试回调函数
【发布时间】:2018-01-16 15:40:11
【问题描述】:

我有一个使用d3 timer 调用的方法。每当调用该方法时,该方法都会发出一个带有几个值的对象。 其中一个值随时间增加。我想编写一个测试来检查这些值是否按升序排列(即是否随时间增加)。

因此,为了解决这个问题,在我的测试中,我订阅了事件发射器,在订阅中,我将收到的对象推送到本地数组中。然后,我期望array[i] 小于array[i+1]。我认为我的逻辑是完全正确的,但我不确定为什么我从 Jasmine 那里得到一个错误,说 the spec has no expectations,即使我有一个。

代码如下:

let x = d3.timer((elapsed) => { 
    this.method(); // call the function
    if(elapsed >= 500) {
     x.stop(); // stops the timer.
    }
});

method(elapsed) {
 // do something
 if(elapsed > 500) {
   this.output.emit({x: somevalue, y: somevalue, f: increasingvalue });
 }
}

茉莉花规格:

it('my spec', inject([JumpService], (service: JumpService) =>{
  array = [];
  //service calls the method
  service.output.subscribe(e => {
   array.push(e);
   // A console statement here will give me the length and the object pushed.
   for(let i = 0; i< array.length - 1; i++) {
    expect(array[i].f).toBeLessThan(array[i+1].f);
   }

  });

}));

我在这里做错了吗?我该如何应对这种情况?请指导我正确的方向。

谢谢。

【问题讨论】:

  • 刚刚相关;我收到此错误是因为我有一个额外的箭头 func 指示器,例如 it('does things', () =&gt; () =&gt; {
  • 如果出于某种原因手动检查,其中使用了“fail(...);,现在支持调用“expect().nothing();”(静音警告)。

标签: javascript angular typescript jasmine jasmine2.0


【解决方案1】:

一般来说,在测试异步回调函数时,在 promise 解决后期待测试的输出总是很重要的。您可以使用 Angular 测试平台框架的 tick()fakeAsync(),或者您可以简单地回退到 Jasmine 使用 done() 测试异步方法的一般方法

使用done()

it('my spec', (done) => {
  array = [];
  service.output.subscribe(e => {
   array.push(e);
   for(let i = 0; i< array.length - 1; i++) {
    expect(array[i].f).toBeLessThan(array[i+1].f);
   }
   done();
  });
});

希望这个答案有所帮助。

注意:我对fakeAsync()tick() 的运气不太好,所以我没有将其包含在答案中。对此感到抱歉。

【讨论】:

    【解决方案2】:

    尝试使用@angular/core/testing 中的async 函数。它

    在异步测试区域中包装测试函数。测试将 当此区域内的所有异步调用时自动完成 完成。可用于包装 {@link injection} 调用。

    请在下面找到代码示例:

    it('...', async(inject([AClass], (object) => {
      object.doSomething.then(() => {
       expect(...);
      })
    });
    

    【讨论】:

      【解决方案3】:

      你应该在 Promise 的末尾使用 done(),但从 Jasmine 2.8.0 开始,这将不起作用,因为没有 done() 方法的实现。你应该像这样测试你的承诺:

      it('does test promise',
          inject([MyService], async (myService: MyService) => {
              const result = await myService.serviceToTest()
              expect(result).not.toBeNull()
              expect(result).toBe('Some Value')
           })
      )
      

      希望对你有帮助

      【讨论】:

        【解决方案4】:

        我成功地使用了 waitForAsync 来包装我的 it 函数。

        it('should display correct data', waitForAsync(() => {
        
            fixture.whenStable().then(() => {
              // expect 
            });
         }));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-10-22
          • 2018-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-18
          • 2017-06-28
          • 2014-12-22
          相关资源
          最近更新 更多