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

zel*_*lda 14 javascript jasmine typescript jasmine2.0 angular

我有一个方法,使用a调用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 });
 }
}
Run Code Online (Sandbox Code Playgroud)

茉莉花规格:

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);
   }

  });

}));
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Ali*_*iuk 11

尝试使用中的async功能@angular/core/testing。它

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

请在下面找到代码示例:

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


She*_*ero 10

通常,在测试异步回调函数时,在解决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();
  });
});
Run Code Online (Sandbox Code Playgroud)

希望这个答案有所帮助

注:我没有用了很大的运气fakeAsync()tick(),所以我不包括它的答案.对于那个很抱歉.


bre*_*ett 5

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

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

    fixture.whenStable().then(() => {
      // expect 
    });
 }));
Run Code Online (Sandbox Code Playgroud)