I'm building an app with React Native. I want to minimize how often I communicate to the database, so I make heavy use of AsyncStorage. There's a lot of room for bugs in the translation between DB and AsyncStorage though. Therefore, I want to make sure that AsyncStorage has the data I believe it does by running automated tests against it. Surprisingly, I haven't found any information on how to do that online. My attempts to do it on my own haven't worked out.
Using Jest:
it("can read asyncstorage", () => {
return AsyncStorage.getItem('foo').then(foo => {
expect(foo).not.toBe("");
}); });
This method failed with an error:
TypeError: RCTAsyncStorage.multiGet is not a function
Removing the return will cause it to run instantly without waiting for the value and improperly pass the test.
I got hit with the exact same error when I tried to test it using the await keyword:
it('can read asyncstorage', async () => {
this.foo = "";
await AsyncStorage.getItem('foo').then(foo => {
this.foo = foo;
});
expect(foo).not.toBe(""); });
Any suggestions on how to successfully run assertions against the values in AsyncStorage? I'd prefer to continue using Jest but if it can only be done with some alternate testing library I'm open to that.
For everyone who sees this question in > 2019:
Since February 2019, AsyncStorage was moved to @react-native-community/async-storage, which causes this warning to appear if you're importing it from
react-native
:The new module includes its own mock, so you don't have to worry about writing your own anymore.
Per the project's documentation, you can set it up in 2 different ways:
With mocks directory
__mocks__/@react-native-community
directory.AsyncStorage
by default in all your tests. If it doesn't, try callingjest.mock(@react-native-community/async-storage)
at the top of your test file.With Jest setup file
package.json
orjest.config.js
) add the setup file's location:Inside your setup file, set up the AsyncStorage mock:
If you're using TypeScript, using the 2nd option (Jest setup file) is way easier, since with the 1st one (mocks directory) it won't associate
@types/react-native-community__async-storage
with the mock automatically.I think jest.setMock could be in this case better than jest.mock so we can use
react-native
with no problem just mocking theAsyncStorage
like that:For anyone else to get here, asyncStorage also needs a callback, some libs use this
May be you can try something like this:
mockStorage.js
and inside your test file:
My original answer just pointed at how the author of react-native-simple-store had dealt with the mocking. I've updated my answer with my own mocking that removes Jason's hard-coded mock responses.
Jason Merino has a nice simple approach to this in https://github.com/jasonmerino/react-native-simple-store/blob/master/tests/index-test.js#L31-L64
My own mock: