Home > OS >  Cannot assign to 'geolocation' because it is a read-only property (angular Jest)
Cannot assign to 'geolocation' because it is a read-only property (angular Jest)

Time:03-21

enter image description hereenter image description hereNot able to assign MockGeolocation return value.

I'm trying to write test cases for AGM map and I found a blockage and was not able to resolve it by myself. Help would be much appreciated. Refer the error message from the screenshot.

CodePudding user response:

Try something like this:

beforeEach(() => {
  (window as any).navigator = mockNavigator;    
});

const mockNavigator = {
  geolocation: {
    getCurrentPosition: () => {},
  }
};

CodePudding user response:

**

Jest is not able a read the type of geolocation. So, I just added the type as Any with the global variable. It worked perfectly for me.

**

 it('should get current location', async () => {

    const handleSpy = jest.spyOn(WhereToBuyComponent.prototype as any, 'setCurrentPosition');
    const mockGeolocation = {
      getCurrentPosition: jest.fn()
        .mockImplementationOnce((success) => Promise.resolve(success({
          coords: {
            latitude: 51.1,
            longitude: 45.3
          }
        })))
    };
    (global as any).navigator.geolocation = mockGeolocation;
    expect(handleSpy).toBeCalled;
  
});
  • Related