I am trying to write the test cases for the below method :-
constructor(private dataSharing: DataSharingService) {
const res: any = this.dataSharing.getSystemUser();
this.systemUserData = res.source._value;
this.systemUserData.systemUserId && this.systemUserData.systemUserId === 1 ? this.disableButton = false : this.disableButton = true;
}
I have tried the below snippet in my spec.ts file for covering the above code :-
fdescribe('ManagePermissionsComponent', () => {
let component: ManagePermissionsComponent;
let fixture: ComponentFixture<ManagePermissionsComponent>;
let dataSharing = jasmine.createSpyObj('DataSharingService', ['getSystemUser']);
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [RouterTestingModule, HttpClientTestingModule],
declarations: [ManagePermissionsComponent],
providers: [
{provide: DataSharingService, dataSharing: roleServiceStub }, SessionStorageService]
})
.compileComponents();
});
beforeEach(() => {
component.systemUserData = dataSharing.getSystemUser.source._value
//component.systemUserData = {'username': '[email protected]', 'firstName': 'Avani', 'lastName': 'Vishwakarma', 'systemUserId': 1, 'isActive': true, 'password' :"Avani123", 'oldPassword':'Avani123', 'email':'[email protected]', 'contact':123, 'imageId':'jpg', 'isAccountLocked':true, 'accountLocked':'dds','accountLockedDate':null, 'loginAttempt':null, 'createdDate':null, 'createdBy':'aparna', 'updatedBy':'jdsjsd', 'updatedDate':null, 'otpGenerated':'dfdsf', 'otpGeneratedDate':'sdsd'};
fixture = TestBed.createComponent(ManagePermissionsComponent);
component = fixture.debugElement.componentInstance;
fixture.detectChanges();
});
But I am getting below error :-
I have added comments below, it should help you.
fdescribe('ManagePermissionsComponent', () => {
let component: ManagePermissionsComponent;
let fixture: ComponentFixture<ManagePermissionsComponent>;
// change this line to just a declaration like so
let dataSharing: jasmine.SpyObj<DataSharingService>;
beforeEach(async () => {
// move the assigning of the spy object here so you have a new
// spy object for every test (beforeEach)
dataSharing = jasmine.createSpyObj<DataSharingService>('DataSharingService', ['getSystemUser']);
await TestBed.configureTestingModule({
imports: [RouterTestingModule, HttpClientTestingModule],
declarations: [ManagePermissionsComponent],
providers: [
// this line was wrong as well, it should be useValue: dataSharing.
// every time the test requires DataSharingService, we provide the mock
{provide: DataSharingService, useValue: dataSharing }, SessionStorageService]
})
.compileComponents();
});
beforeEach(() => {
// need to mock getSystemUser before createComponent because
// we need it for the constructor.
// mock _value however you like
dataSharing.getSystemUser.and.returnValue({ source: { _value: {} }});
fixture = TestBed.createComponent(ManagePermissionsComponent);
component = fixture.debugElement.componentInstance;
fixture.detectChanges();
});