'angular Jasmine - cannot set property of undefined
My component code:
public save() {
this.gridService.gridCellUpdated = false;
}
My Jasmine code
class GridServiceMock {
public gridCellUpdated = false;
}
let gridService: GridService;
beforeEach(
async(() => {
TestBed.configureTestingModule({
declarations: [ModalComponent, BsModalDirective],
providers: [{ provide: GridService, use: GridServiceMock }]
})
.compileComponents();
});
);
it('should save assets', () => {
gridService = fixture.debugElement.injector.get(GridService);
component.save();
expect(gridService.gridCellUpdated).toBeFalsy();
});
My error:
TypeError: Cannot set property 'gridCellUpdated' of undefined
Edit: Updated the code by following below solutions but still get the same error.
Solution 1:[1]
as @Vega mentioned in his comment: the service is not a property of the component. It will be injected.
Your setup of the Testing Module is correct and you can get the service from the Testbed like this:
let gridService: GridService;
let fixture: ComponentFixture<ModalComponent>;
let component: ModalComponent;
TestBed.configureTestingModule({...});
TestBed.compileComponents().then(() => {
fixture = TestBed.createComponent( ModalComponent );
component = fixture.debugElement.componentInstance;
gridService= fixture.debugElement.injector.get( GridService );
} );
It will get an instance of the GridService as GridServiceMock. Your test should success now.
Regards
Solution 2:[2]
Spent 15 mins trying to find out why this was happening only to find out I had missed to declare the it() block and directly writing my test case statements inside describe() block. Make sure your statements are inside it() block.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alfredson |
| Solution 2 | Luther |
