Xyn
Xyn

Reputation: 51

ng-mocks MockBuilder / MockRender with injected (real) service

I am attempting to independently test a child component that requires a FormGroup as input, as the child represents a section on the parent form. We use an in-house framework that relies on an entity / entity service hierarchy to automagically build the forms for us, which is very nice, as these are large forms and would be incredibly tedious to do by hand. So I need to actually inject the parent entity service in order to build the form I need to test the child component, and thus far I have been unable to make it work. The below is a sample of what I'm trying to do:

beforeEach(() => {
  return MockBuilder(ChildComponent, [
    SharedModule,
    LazyLoadedModule
   ])
    .keep(ParentEntityService);
});

it('should create', () => {
  const fixture = MockRender(ChildComponent);
  const service = fixture.point.injector.get(ParentEntityService);
  const formGroup = service.createForm(...);
  fixture.componentInstance.formGroup = formGroup;
  fixture.detectChanges();
  expect(fixture.point.componentInstance).toBeTruthy();
});

The main problem I'm having is that as soon as MockRender is called, console.log() just stops working, so I can't see the value of fixture or anything I'm trying to do - I'm not sure why.

If anyone can help I'd appreciate it.

EDIT: I've added a StackBlitz where I've replicated the issue as best I could without revealing closed source code. https://stackblitz.com/edit/ng-mocks-sandbox-crrf85

As you can see, the test blows up when the ngOnInit runs as the FormGroup passed to the child component is undefined. The issue is that the service should be building the form. With regular angular tests and TestBed.inject before calling the service, it works fine, but I want to use ng-mocks so I can mock everything but whatever I'm testing and the service.

Upvotes: 3

Views: 3191

Answers (1)

satanTime
satanTime

Reputation: 13574

As discussed in gitter and based on the min repo you provided.

if you cannot mock the forms generation, you should .keep all dependencies which help to build them.

There is a passing example of your test: https://stackblitz.com/edit/ng-mocks-sandbox-8amzcu?file=src%2Ftests%2Fservice-create-form%2Ftest.spec.ts

What I changed:

  • added .keep(ReactiveFormsModule)
  • added .keep(FormBuilder)
  • disabled change detection on MockRender(ChildComponent, null, false);, because render depends on the correct value of fixture.componentInstance.formGroup.

I can see the test is green now.

Upvotes: 0

Related Questions