Maloric
Maloric

Reputation: 5615

Is it possible to test for the presence of a custom directive attribute in Angular 2?

For instance, I have a custom directive called featureFlag, which shows or hides an element depending on the configuration of that feature:

<div *myFeatureFlag="'myFeatureName'">
    This should be hidden if the myFeatureName feature is turned off.
</div>

When it comes to testing this, however, I'm at a loss. I already know how to test the directive itself, but I want to test that *myFeatureFlag is added to an element, without testing the logic inside of the myFeatureFlag directive.

Is there a way to check for the existence of this directive in my unit test? Something like this:

it('should be wrapped in a feature flag', () => {
    expect(element.querySelector('div').myFeatureFlag).toEqual("'myFeatureName'");
});

Upvotes: 2

Views: 888

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208984

Here's an ugly way, but it works. When Angular creates the bindings, it adds some comments to the HTML

<!--template bindings={
  "ng-reflect-my-feature-flag": "myFeatureName"
}-->

What you can do is parse it with some regex and grab the JSON. Then just check the value

function getFeatureFlagBinding(el: any) {
  return JSON
    .parse((/template bindings=(\{[\s\S]*?\})/g)
      .exec(el.nativeElement.previousSibling.textContent)[1])['ng-reflect-my-feature-flag'];
}

it('should be wrapped in a feature flag', () => {
  let fixture = TestBed.createComponent(TestComponent);
  fixture.detectChanges();
  let el = fixture.debugElement.nativeElement;

  let div = fixture.debugElement.queryAll(n => n.name === 'div')[0];
  expect(getFeatureFlagBinding(div)).toBe('myFeatureName');
});

Upvotes: 2

Related Questions