Kushal Jayswal
Kushal Jayswal

Reputation: 933

Angular 4 - How to parse hyphened variable in template for Karma testing?

I am facing an issue while unit testing my Angular 4 component with Karma. Below is the command I am running to test:

tsc && karma start --browsers PhantomJS

I have hyphened variable as below, which is bound with the HTML template and I verified the bind is working and data displays on the page (in browser).

Hyphned variable - in a component.ts file

template-variable-key

But during the unit testing, I am facing an issue as it gives below error:

TypeError: Cannot read property 'layout-permission-title-key' of undefined

How I defined in HTML template

(1) In template with EXPRESSION
<p>{{error['template-variable-key']}}</p>
(2) OR In template with data binding using innerHtml
<p [innerHtml]="error['template-variable-key']"></p> <!-- or -->

<p [innerHtml]="error?.template-variable-key"></p>

Note: As the same hyphened variable is being used at many places other than Angular, I cannot change it to camelCase or something else.

(1) and (2) both didn't work for me.

Thanks in advance for your answer :)

Upvotes: 0

Views: 234

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21638

Another thing you can try is but an *ngIf="error" on anywhere that tries to use the error property

<p *ngIf="error" [innerHtml]="error['template-variable-key']"></p>

The binding is looking for a property called error and that is undefined so when it tries to access template-variable-key you get the undefined error.

You need to mock the error object on you component.

Usually your spec files you have a section like have a section like this in your spec file

let component: YourComponentType;
let fixture: ComponentFixture<YourComponentType>;

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ YourComponentType ]
  })
  .compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(YourComponentType);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

In the second before each you can mock the error object with

component = fixture.componentInstance;
component.error = { };
component.error['template-variable-key'] = 'Your test data';

Or in your component just have a default for the error object with

error = {};

Upvotes: 1

Related Questions