user1938143
user1938143

Reputation: 1184

How to mock variables in a template in a Jest unit test for an Angular application?

I meet a problem in a jest unit test.

the code for the html looks jest like this:

<ng-container *ngVar="personFacade.personInfo$ | async as personInfo">
 @if (personInfo.active){
  <childcomponent1></childcomponent1>
 }@else 
{ <childcomponent2></childcomponent2>
}
</ng-container>

the logic is simple.

in my jest test, I have mock this personfacde and return a mock value for personInfo.

  function mockPersonInfo(): jest.Mock<any, any> {
    return MockInstance(PersonFacade, 'personInfo$', jest.fn(), 'get').mockReturnValue(of(personInfo));
  }

and in the test I want to check if personInfo active = false should only childcomponent2 will be shown.

and my test looks like this:


it('should show only childcomponent2', () => {
 mockPersonInfo();
 component = fixture.point.componentInstance;
 fixture.detectChanges();

  const childcomponent1 = ngMocks.find('childcomponent1');
  expect(childcomponent1).toBeFalsy();
});

but I got error message: Cannot find an element via ngMocks.find('childcomponent1')

If I move e.g childcomponent1 out of the ng-container, the test can find this component1.

so I assume that there is some problem with mocking data in ng-container.

Upvotes: 1

Views: 178

Answers (1)

Naren Murali
Naren Murali

Reputation: 58394

Could you try changing it to, we are mocking the facade after the component is initialized, which might be the problem is my understanding.

function mockPersonInfo(component): jest.Mock<any, any> {
    return MockInstance(component.personFacade, 'personInfo$', jest.fn(), 'get').mockReturnValue(of(personInfo));
}

Then call it like

it('should show only childcomponent2', () => {
 mockPersonInfo(component);
 component = fixture.point.componentInstance;
 fixture.detectChanges();

  const childcomponent1 = ngMocks.find('childcomponent1');
  expect(childcomponent1).toBeFalsy();
});

Upvotes: 0

Related Questions