0
    @Input()
    public set isRunning(value: boolean) {
        if (!value) {
            this.cancelTimeout();
            this.isDelayedRunning = false;
            return;
        }

        if (this.currentTimeout) {
            return;
        }

        this.currentTimeout = setTimeout(() => {
            this.isDelayedRunning = value;
            this.cancelTimeout();
        }, this.delay);
    }

The code above is an @Input for an angular 2 component. I have a problem in creating a test case for the input as I do not know how to create a test for this kind of input. Should I create a getter? How do I do this? I cannot find any reference for this.

1 Answer 1

1

With a setter (set), all you do is assign the value to the property (method)

let fixture = TestBed.createComponent(TestComponent);
let component = fixture.componentInstance;l
component.isRunning = true;
fixture.detectChanges();

For the timeout, you might need to do something like

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

it('should change isDelayedRunning', fakeAsync(() => {
  let fixture = TestBed.createComponent(TestComponent);
  let component = fixture.componentInstance;
  fixture.detectChanges();

  component.isRunning = true;
  // wait for timeout
  tick(200);
  fixture.detectChanges();
  expect(fixture.componentInstance.isDelayedRunning).toBe(true);
}));

fakeAsync won't work if you are using templateUrl in your component. So you have to use async. But AFAIK, there's no facility like tick where we can control the wait period, so you might have to just set a timeout in the test

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

it('should change isDelayedRunning', async(() => {
  let fixture = TestBed.createComponent(TestComponent);
  let component = fixture.componentInstance;
  fixture.detectChanges();

  component.isRunning = true;
  setTimeout(() => {
    fixture.detectChanges();
    expect(fixture.componentInstance.isDelayedRunning).toBe(true);
  }, 200);
}));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.