简体   繁体   中英

How to mock npm package methods in react native jest?

I'm developing react native app, in that i'm using two packages for exiting and restarting my app. Whenever I tries to mock these functions in getting error. I'm not able to cover test cases for exit and restart methods Could anybody know how do we mock these functions

import RNRestart from 'react-native-restart';
import RNExitApp from 'react-native-exit-app';

if (configNotThere) {
   RNExitApp.exitApp();
}

if(configFound){
 RNRestart.Restart();
}

Jest code

jest.mock('react-native-exit-app', () => ({
  RNExitApp: {
    exitApp: () => jest.fn(),
  },
}));

expect(exitApp).toHaveBeenCalledTimes(1);
// expect(RNExitApp.exitApp()).toHaveBeenCalledTimes(1);
// beforeEach(() => {
//   const exitAppMockValue = jest.fn();
//   exSpy.mockReturnValue(exitAppMockValue);
// });
// const dummyExit = jest.fn();
// rnExitMock.mockReturnValue(dummyExit);

// RNExitApp.exitApp().mockResolvedValueOnce();

// const component = shallow(<KfcAppError />);
// component.find(TouchableOpacity).forEach((element) => {
//   element.simulate('press');
// });

//  RNExitApp.exitApp().mockResolvedValueOnce(true);

tried with all the way BUT no luck for always some of the getting errors

How to mock npm package methods in jest ? Please anybody help me on this

react native exit app npm package react native restart app npm package

I have come up with below answer for mocking npm module methods In setup.js file we need to declare the methods like below then it will detect the methods in any of test.js files

jest.mock('react-native-exit-app', () => ({
   exitApp: () => jest.fn(),
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM