I am trying to run a simple test in my Angular application that must add or remove permissions from an array and make a call to the backend for it.
The issue is that once the component’s function that manage the permission change is execute, the component’s property that manage the permissions array get’s empty.
Here is the test:
describe('PermissionsTableComponent', () => {
let component: PermissionsTableComponent;
let fixture: ComponentFixture<PermissionsTableComponent>;
let mockService: any;
beforeEach(waitForAsync(() => {
mockService = jasmine.createSpyObj('PermissionsService', ['getCategoryWithPermissions', 'getRoles', 'addRolePermission', 'deleteRolePermission']);
mockService.getCategoryWithPermissions.and.returnValue(Promise.resolve([]));
mockService.getRoles.and.returnValue(Promise.resolve([]));
mockService.addRolePermission.and.returnValue(Promise.resolve());
mockService.deleteRolePermission.and.returnValue(Promise.resolve());
TestBed.configureTestingModule({
imports: [PermissionsTableComponent, KeysPipe],
providers: [{ provide: PermissionService, useValue: mockService }],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PermissionsTableComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should add permission', async () => {
component.roles = [{ id: 1, description: 'Role 1', permissions: [] }];
fixture.detectChanges();
const event = { target: { checked: true } } as unknown as Event;
console.log(component.roles);
await component.onPermissionChange(1, 1, event);
console.log(component.roles);
expect(component.roles[0].permissions).toContain(1);
});
it('should remove permission', async () => {
component.roles = [{ id: 1, description: 'Role 1', permissions: [1] }];
fixture.detectChanges();
const event = { target: { checked: false } } as unknown as Event;
await component.onPermissionChange(1, 1, event);
expect(component.roles[0].permissions).not.toContain(1);
});
});
When the test is execute none of them succeed as in the first log the component.roles
result to be: [Object{id: 1, description: 'Role 1', permissions: []}]
but once onPermissionChange()
is run roles
become an empty array.
The code:
async onPermissionChange(roleId: number, permissionId: number, event: Event): Promise<void> {
const role = this.roles.find((role) => role.id === roleId);
if (!role) {
return;
}
const target = event.target as HTMLInputElement;
try {
if (target.checked) {
role.permissions.push(permissionId);
await this.service.addRolePermission(roleId, permissionId);
} else {
role.permissions = role.permissions.filter((id) => id !== permissionId);
await this.service.deleteRolePermission(roleId, permissionId);
}
} catch (error) {
target.checked = !target.checked;
}
}