Spec has no expectations - Jasmine testing the callback function

前端 未结 3 1161
清酒与你
清酒与你 2020-12-20 10:59

I have a method which is being called using a d3 timer. Whenever the method is called, the method emits an object with a couple of values. One of the values in

相关标签:
3条回答
  • 2020-12-20 11:38

    Try using async function from @angular/core/testing. It

    Wraps a test function in an asynchronous test zone. The test will automatically complete when all asynchronous calls within this zone are done. Can be used to wrap an {@link inject} call.

    Please find code example below:

    it('...', async(inject([AClass], (object) => {
      object.doSomething.then(() => {
       expect(...);
      })
    });
    
    0 讨论(0)
  • 2020-12-20 11:48

    In general, when testing the async callback functions, it is always important to expect the outputs of the test after the promises are resolved. You can use the Angular test bed framework's tick() with the fakeAsync() or you can simply fallback to the Jasmine's general way of testing the async methods by using done()

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

    Hope this answer helps.

    Note: I didn't had great luck with the fakeAsync() and tick(), so I am not including it in the answer. Sorry about that.

    0 讨论(0)
  • 2020-12-20 11:52

    You should use done() at the end of the promise, but from Jasmine 2.8.0 that will not work because there is not implementation for a done() method. You should test your promises like:

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

    Hope that this help you

    0 讨论(0)
提交回复
热议问题