I am using my own created component. What app-button.ts
does it that it check for current user roles and then renders if it match the define roles.
ButtonType is just to define what style to use.
demo.ts:
<app-button
buttonText="BACK"
(clickEvent)="goBack()"
[buttonType]="'secondary'"
>
</app-button>
app-button button implementation:
<button *ngIf="canRender" class="{{ buttonClass }}" (click)="onClickEvent()" [disabled]="disabled">
<span class="{{ spanClass }}">{{ buttonText }}</span>
</button>
app-button.ts file:
export class PrimaryButtonComponent implements OnInit {
@Input() buttonText: string;
@Input() disabled? = false;
@Input() allowedRoles: Role[] = [];
@Input() buttonType = 'primary';
canRender? = false;
buttonClass: string;
spanClass: string;
@Output() clickEvent = new EventEmitter();
constructor(private credentialsService: CredentialsService) {}
ngOnInit() {
if (this.allowedRoles.length !== 0) {
const currentUserRoles: Role[] = this.credentialsService.currentUserValue.role.slice();
this.canRender = allowedToAccess(this.allowedRoles, currentUserRoles);
} else {
this.canRender = true;
}
if (this.buttonType === 'primary') {
this.buttonClass = 'primary-button';
this.spanClass = 'primary-button-text';
}
if (this.buttonType === 'secondary') {
this.buttonClass = 'secondary-button';
this.spanClass = 'secondary-button-text';
}
}
onClickEvent() {
this.clickEvent.emit();
}
}
Unit Test:
fit('should navigate back to dashboard when click back button', async(() => {
const onClickSpy = spyOn(component, 'goBack').and.callThrough();
const routerSpy = spyOn(router, 'navigate');
// Click Back button
const button = fixture.debugElement.query(By.css('.secondary-button'));
expect(button).not.toBeNull();
}));
when i am doing my unit test, I am seeing this error
Error: Expected null not to be null.
But my actual UI is showing the component. how can it be null in test?
In TestBed.configureTestingModule
, in the declarations
array, add ButtonComponent
(assuming ButtonComponent
is what it is called as the class). After doing this, expect(button).not.toBeNull();
should be good to go.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.