help-me-mom / ng-mocks

Angular testing library for mocking components, directives, pipes, services and facilitating TestBed setup
https://www.npmjs.com/package/ng-mocks
MIT License
1.05k stars 76 forks source link

ControlContainer not injected #164

Closed appienvanveen closed 4 years ago

appienvanveen commented 4 years ago

Hi,

First my compliments to your library. All looks super easy and until so far everything worked perfectly :)

However I dont understand why my test below fails. Please note its pseudo code.

Code

import {Component} from '@angular/core';
import {ControlContainer} from '@angular/forms';

@Component({
  selector: 'xxxx',
  templateUrl: './xxxl',
  styleUrls: ['./xxx'],
})
export class XComponent{

  constructor(public controlContainer: ControlContainer) {
  }

}

Test

const fg: FormGroup = new FormGroup({
    x: new FormControl(''),
});

const fgd: FormGroupDirective = new FormGroupDirective([], []);
fgd.form = fg;
describe('XComponent', () => {
    let component: XComponent;
    let fixture: ComponentFixture<XComponent>;

    beforeEach(() => MockBuilder(XComponent, XModule)
        .provide({provide: ControlContainer, useValue: fgd})
        .build()
    );

    beforeEach(() => {
         fixture = MockRender(XComponent);
         component = fixture.componentInstance;
         fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
        expect(component.controlContainer).toBeDefined();        <---- this assertion fails
    });
});
satanTime commented 4 years ago

Hi,

thanks for the report,

component.componentInstance points to a middle component for render. If you want to access XComponent you need to do it via component.point.componentInstance, that should solve the issue. But this requires a proper type declaration: let fixture: MockedComponentFixture<XComponent>.

The problem is that properties aren't proxied to the middle component due to their missed definition in Object.getOwnPropertyNames.

Please let me know how it works for you.

appienvanveen commented 4 years ago

Perfect! I've should have read the docs better.

Thanks for the quick response :)

satanTime commented 4 years ago

Feel free to ask any questions, I also updated my comment to point to .componentInstance instead of .controlContainer.