繁体   English   中英

规范没有期望 - Jasmine 测试回调函数

[英]Spec has no expectations - Jasmine testing the callback function

我有一个使用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);
   }

  });

}));

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

谢谢。

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

使用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()运气不佳,所以我没有将它包含在答案中。 对此感到抱歉。

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

将测试功能包装在异步测试区中。 当该区域内的所有异步调用完成后,测试将自动完成。 可用于包装 {@link 注入} 调用。

请在下面找到代码示例:

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

您应该在承诺的末尾使用 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')
     })
)

希望这对你有帮助

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

it('should display correct data', waitForAsync(() => {

    fixture.whenStable().then(() => {
      // expect 
    });
 }));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM