Angular 2 fakeAsync expects timeout in function with tick ()?

I am trying to get results from a dummy backend in Angular 2 for unit testing. We are currently using fakeAsynca timeout to simulate time.

current working unit test

it('timeout (fakeAsync/tick)', fakeAsync(() => {
    counter.getTimeout();
    tick(3000); //manually specify the waiting time
}));

But this means that we are limited by a manually defined timeout. Not after completing an asynchronous task. What I'm trying to do is make it tick()wait for the task to complete before continuing with testing.

This does not seem to work as intended.

Reading on fakeAsyncand the tickanswer here explains that:

tick () imitates the asynchronous course of time.

I created a plnkr example simulating this scenario.

getTimeout() -. tick() getTimeout().

counter.ts

getTimeout() {
  setTimeout(() => {
    console.log('timeout')
  },3000)
}

counter.specs.ts

it('timeout (fakeAsync/tick)', fakeAsync(() => {
    counter.getTimeout();
    tick();
}));

": 1 ".

- ?

tick() , -? , ?

+9
5

:

 fixture.destroy();
 flush();
+2

:

// I had to do this:
it('timeout (fakeAsync/tick)', (done) => {
  fixture.whenStable().then(() => {
       counter.getTimeout();
       tick();
    done();
  });
});

+1

flushMicrotasks . , tick() flushMicrotasks, jasmine tick().

0

fakeAsync - . tick - , , . , async whenStable, , 3 , .

, counter.spec.ts , , 0 ( ). , , , . , , - .

, , fakeAsync tick , . - , , - setTimeout setTimeout , , , .

, , , , , . :

tick(Infinity);

, . ,

discardPeriodicTasks();

.

0

test.service.ts

export class TestService {
  getTimeout() {
    setTimeout(() => { console.log("test") }, 3000);
  }
}

test.service.spec.ts

import { TestBed, async } from '@angular/core/testing';

describe("TestService", () => {
  let service: TestService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [TestService],
    });

    service = TestBed.get(TestService);
  });

  it("timeout test", async(() => {
    service.getTimeout();
  });
});

test.service.ts

export class TestService {
  readonly WAIT_TIME = 3000;

  getTimeout() {
    setTimeout(() => { console.log("test") }, this.WAIT_TIME);
  }
}

test.service.spec.ts

import { TestBed, fakeAsync } from '@angular/core/testing';

describe("TestService", () => {
  let service: TestService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [TestService],
    });

    service = TestBed.get(TestService);
  });

  it("timeout test", fakeAsync(() => {
    service.getTimeout();
    tick(service.WAIT_TIME + 10);
  });
});
-1
source

Source: https://habr.com/ru/post/1673373/


All Articles