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

时间:2017-08-08 22:30:04

标签: javascript angular typescript jasmine jasmine2.0

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

  });

}));

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

谢谢。

4 个答案:

答案 0 :(得分:9)

通常,在测试异步回调函数时,在解决promise之后期望测试的输出始终很重要。您可以将Angular测试床框架的tick()fakeAsync()一起使用,或者您可以使用done()

简单地回退到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()没有好运,所以我不在答案中。对不起。

答案 1 :(得分:6)

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

  

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

请在下面找到代码示例:

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

答案 2 :(得分:0)

您应该在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')
     })
)

希望这对您有帮助

答案 3 :(得分:0)

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

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

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