-1

I am learning React Native and Jest testing.

I have a piece of code where I am storing some value in an AsyncStorage when a button is clicked. When the button is clicked I call the below method.

saveState = () => {
    AsyncStorage.setItem('saveState', 'button clicked');      
}

Now I would want to unit test the above method to see if my Async storage is working fine or not.

I was able to create a snapshot and also test remaining functionalities of the method but not this one. But I am not quite familiar in how to do so?

2nd edit ------

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


describe('<MyComponent/>', () => {
  let tnCScreen
  let props
  let instance

  beforeEach(() => {
    tnCScreen = shallow(<MyComponent {...props} />)
    instance = tnCScreen.instance()
  })

  test('test saveState method is called', () => {
    expect(instance.saveState()).toBeCalled
    expect(AsyncStorage.setItem).toBeCalledWith('saveState', 'button clicked');
  })

})

When I try the above I get below error

expect(received).toBeCalledWith(...expected)
Matcher error: received value must be a mock or spy function
Received has value: undefined
akash89
  • 881
  • 3
  • 12
  • 31
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Apr 11 '20 at 12:55

1 Answers1

3

In your test file, you can mock any external module and then check that it was called with the right arguments like so:

jest.mock('@react-native-community/async-storage', () => ({
  setItem: jest.fn(),
}));

// in your test:
expect(AsyncStorage.setItem).toBeCalledWith('saveState', 'button clicked');

Marek Lisik
  • 2,003
  • 1
  • 8
  • 17
  • Hi Marek, I have edited the above with the solution you have provided, but I get the above error. Also, I could not change to '@react-native-community/async-storage' as our project is using Async storage from react native. Apart from that any guesses what could be going wrong? – akash89 Apr 11 '20 at 15:04
  • I understand you are importing AsyncStorage from react-native? It is now deprecated, so if that is the case, consider adding the `@react-native-community/async-storage` package and then adjusting the jest.mock to what I provided above. Otherwise, this past question can also help: https://stackoverflow.com/questions/40952566/how-to-test-async-storage-with-jest – Marek Lisik Apr 11 '20 at 15:35