Bojidari
Bojidari

Reputation: 155

how to get Inner text from component instance when testing Karma

I have a component and a simple button

<cc-button >SUBMIT</cc-button> => Component
<button id="save-button">SUBMIT</button> => HTMLButtonElement

I have to create a test to check if the inner text for both is accurate.

so when i write:

de.query(By.css('#save-button')).nativeElement.innerText 

I accurately receive the string but when I target the component selector like:

de.query(By.css('cc-button')).nativeElement

I see just an empty element, componentInstance is not helping as well as it just gives me access to the components properties which is not what is needed at this case.

Any ideas how to get it

Upvotes: 0

Views: 679

Answers (1)

Bojidari
Bojidari

Reputation: 155

I found a solution to my question.

In my case I want to get the innerText of a component that is being used in the HTML. In order to escape the testing error

context.js:265 NG0303: Can't bind to 'type' since it isn't a known property of 'cc-button' (used in the 'ActionsComponent' component template).
1. If 'cc-button' is an Angular component and it has the 'type' input, then verify that it is a part of an @NgModule where this component is declared.
2. If 'cc-button' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

Im creating a Stub for this component which looks like this:

@Component({
    selector: 'cc-button',
    template: '',
})

export class CcButtonStub {
    @Input() public pressed;
    @Input() public disabled;
    @Input() public type;
}

the gotcha here is that in the template of the stub im creating an empty string and when karma reads this it assumes that there is no string there only the component properties are read. the solution is to add an ng-content in the stub and tell it that there should be some kind of content, hence it should look like this:

@Component({
    selector: 'cc-button',
    template: '<ng-content></ng-content>',
})

now you can check if the given element has the correct text based on conditions.

Upvotes: 0

Related Questions