简体   繁体   中英

Angular 2(4) component with ControlValueAccessor testing

I would like to test component which implements ControlValueAccessor interface for allow to use [(ngModel)] in my custom component, but the issue is that usual inputs comes correct but ngModel - undefined . Here is code example:

@Component({
  template: `
    <custom-component
      [usualInput]="usualInput"
      [(ngModel)]="modelValue"
    ></custom-component>`
})

class TestHostComponent {
  usualInput: number = 1;
  modelValue: number = 2;
}

describe('Component test', () => {
  let component: TestHostComponent;
  let fixture: ComponentFixture<TestHostComponent>;
  let de: DebugElement;
  let customComponent: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        CustomComponent,
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  }));
});

So, I expect usualInput Input() value in my customComponent will equal 1 (it is true), and ngModel value will equal 2, but ngModel = undefined and after debug I know that ControlValueAccessor writeValue method doesn't call in test environment (but it works correct for browser). So how can I fix it?

Inside your ControlValueAccessor component you do not have access to ngModel unless you injected it and did some tricks to avoid circular dependency.

ControlValueAccessor has writeValue method which receives values from control when it is updated — if you need, you can store this value in your component and then test it.

You have to wrap your test with async, and wait for fixture.whenStable

 it('should get ngModel', async(() => { let customComponent = debugEl.query(By.directive(CustomComponent)); fixture.whenStable().then(() => { fixture.detectChanges(); expect(customComponent.componentInstance.value).toEqual(2); }); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM