Z
Z
zlodiak2021-03-19 14:10:25
Angular
zlodiak, 2021-03-19 14:10:25

How to simulate delay?

There is a service that contains the state:

@Injectable({
  providedIn: 'root'
})
export class WordsService {

  words: string[] = [
    'qqq',
    'www',
    'eee',
    'rrr',
    'ttt',
    'yyy',
  ];

  constructor() { }

}


The component has a button, after clicking on which the state from the service is displayed in the component template:
@Component({
  selector: 'app-page3',
  template: `
    <div *ngFor="let word of serviceWords" class="word-el">
        {{ word }}
    </div>
    <button (click)="getWordsFromService()" id="getWordsBtn">get words from service</button>
  `,
  styleUrls: ['./page3.component.scss']
})
export class Page3Component {
  serviceWords: string[] = [];
  constructor(private wordsService: WordsService) { }
  getWordsFromService() {
    this.serviceWords = this.wordsService.words;
  }
}


I'm trying to simulate a click on a button and check if the data from the service is displayed in the template.

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [ Page3Component ]
  })
  .compileComponents();
});

it('should display list after getWords-button', () => {
  fixture.detectChanges();
  const compliedComponent = fixture.debugElement.nativeElement;

  const btn = compliedComponent.querySelector('#getWordsBtn');
  btn.dispatchEvent(new Event('click'));

  setTimeout(() => {
    expect(compliedComponent.querySelector('.word-el')).toBeTruthy();  
  }, 1000);
});


With this test, everything is OK, it ends successfully. But I don't like the setTimeout construct.

Can you please tell me if it can be replaced with something else? The fact is that in it I used a time delay of 1000, which is bad because I registered it at random. The 100ms delay still works, but the 1ms delay no longer works. Such magic numbers are highly undesirable.

I tried to do like this:
tick();
expect(compliedComponent.querySelector('.word-el')).toBeTruthy();


so:

waits();
expect(compliedComponent.querySelector('.word-el')).toBeTruthy();


But to no avail

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2021-03-22
@Xuxicheta

tick must be inside fakeAsync and it takes time too.
You can await fixture.whenStable()
also inside fakeAsync

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question