Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 935
qwe asd Avatar asked Jun 16 '17 09:06

qwe asd


1 Answers

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.

like image 108
waterplea Avatar answered Oct 13 '22 01:10

waterplea