Argument of type '"openURL"' is not assignable to parameter of type 'never' using Jest

Viewed 319

I am beginner in Jest and these are classes defined. APIService class is not exported; only openURL function is defined.

APIService.ts

    export const openURL = async (openURL : string) => {
    await Linking.openURL(openURL );
};

RegistrationPage.tsx

import{openURL} from '../APIService';

RegistrationPage.test.ts

test('should call function openURL with empty value', async () => {
const url = '';
const mockOpenURL = jest.fn();
mockOpenURL .mockImplementation(() => Promise.resolve(''));
const openURLSpy = jest.spyOn(openURL, 'openURL');
const mockURL = await openURL(url);
expect(mockOpenURL).toBeCalled();
expect(mockURL).toEqual(url);
expect(mockOpenURL).toHaveBeenCalledWith(url);
openURLSpy.mockRestore();

});

After writing this function as per my understating may be it has loopholes not having properly mocked or spyed running it causing an error for Argument of type '"openURL"' is not assignable to parameter of type 'never' using Jest

suggestions to improve this testcase will be helpful.

2 Answers

Just defining a variable locally like const mockOpenURL = jest.fn() cannot mock anything.

jest.spyOn(openURL, 'openURL') fails because openURL is a function and there's there's no openURL.openURL property.

It's APIService module that needs to be mocked:

import{openURL} from '../APIService';
jest.mock('../APIService', () => {
  return {
    __esModule: true,
    openURL: jest.fn()
  }
};
...
openURL.mockResolvedValue();
// code that calls openURL

Thank you @ jest.mock('../APIService.ts', () => { return { __esModule: true, openURL: jest.fn(), }; });

test('openURL function to be called with', async () => {
    const openURL = 'www.google.com';
    const openURL = jest.fn();
    openURL.mockReturnValue(openURL );
  });
Related