question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Getting [@RNC/AsyncStorage]: NativeModule: AsyncStorage is null. when running jest

See original GitHub issue

Current behavior

I have two tests running with jest on react native code. One is for a component and one is for a service. Both are not using AsyncStorage but calling other classes, which do that. For simplicity I give you here the code for the Service, the class, which is called by the Service and the test for the Service. UserService:

import request from './request'
import * as Constants from '../../utils/Constants'

function getUser() {
    return request({
        url: Constants.USER,
        method: 'GET'
    }, true)
}

function login(user) {
    return request({
        url: Constants.LOGIN,
        method: 'POST',
        data: user
    }, false)
}

const UserService = {
    login, getUser
};

export default UserService;

request:

import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';
import * as Constants from './../../utils/Constants'


/**
 * Request Wrapper with default success/error actions
 */

const request = async function (options, isHeader = true) {

let token = null;
let header = null;
if (isHeader) {
    token = await AsyncStorage.getItem("Auth"); /// Add header
    header = {
        // add special header to XHR requests
        'X-Requested-With': 'XMLHttpRequest',
        // add authorization
        'Authorization': `${JSON.parse(token).token}`
      }
}

const client = axios.create({
    baseURL: Constants.BASE_URL,
    headers: header

});

const onSuccess = function (response) {

    console.log('Request Successful!', response);
    return response.data;
}

const onError = function (error) {
    console.log('Request Failed:', error.config);

    if (error.response) {
        // Request was made but server responded with something
        // other than 2xx
        console.debug('Status:', error.response.status);
        console.debug('Data:', error.response.data);
        console.debug('Headers:', error.response.headers);

    } else {
        // Something else happened while setting up the request
        // triggered the error
        console.debug('Error Message:', error.message);
    }

    return Promise.reject(error.response || error.message);
}


return client(options)
    .then(onSuccess)
    .catch(onError);
}

export default request;

The test for UserService:

import mockAxios from 'jest-mock-axios';
import * as Constants from './../../utils/Constants'
import UserService from './UserService';
import sinon from 'sinon';
import MockStorage from './../../test/MockStorage';

const storageCache = {};
const AsyncStorage = new MockStorage(storageCache);

jest.setMock('AsyncStorage', AsyncStorage)

afterEach(() => {
    mockAxios.reset();
})

describe('UserService', () => {
    it('getUser should call axios get', async () => {
      const expectedUrl = `${Constants.BASE_URL}${Constants.USER}`;
      const user = {user:'test', password: 'test'};
      const expectedCallArgs = {
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      };
     var spy = sinon.spy(AsyncStorage, "getItem");
     await UserService.getUser();

     expect(mockAxios.get).toHaveBeenCalledWith(expectedUrl, expectedCallArgs);
     expect(spy.calledOnce).toBeTruthy();
     mockAxios.mockResponse({data: user});
    });
});

When running the test, I´m getting this error:

[@RNC/AsyncStorage]: NativeModule: AsyncStorage is null.

There are also steps written down to fix this issue, but none of them helped.

Expected behavior

The expected behavior would be, that AsyncStorage is used and is not null.

Repro steps

  • creating a project with react-native init
  • running react-native start
  • running react-native run-android (after this two steps app works like expected)
  • running npm run test (which runs jest)

Environment

  • Async Storage version: 1.6.1

  • React-Native version: 0.60.4

  • Platform tested: Android

  • Logs/Error that are relevant: Test suite failed to run

    [@RNC/AsyncStorage]: NativeModule: AsyncStorage is null.

    To fix this issue try these steps:

    • Run `react-native link @react-native-community/async-storage` in the project root.
    
    • Rebuild and restart the app.
    
    • Run the packager with `--clearCache` flag.
    
    • If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app.
    
    • If this happens while testing with Jest, check out docs how to integrate AsyncStorage with it: https://github.com/react-native-community/async-storage/blob/LEGACY/docs/Jest-integration.md
    

    If none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-community/react-native-async-storage/issues

    at Object.<anonymous> (node_modules/@react-native-community/async-storage/lib/AsyncStorage.js:22:9)
    at Object.<anonymous> (node_modules/@react-native-community/async-storage/lib/index.js:5:1)
    

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:15
  • Comments:14 (1 by maintainers)

github_iconTop GitHub Comments

32reactions
Wpdascommented, Jan 19, 2021

Inside the ./src/, create __mocks__/@react-native-community/async-storage.js

Place this content inside the async-storage.js file: export default from '@react-native-community/async-storage/jest/async-storage-mock'

Your tests should work fine now.

21reactions
jchookcommented, Dec 6, 2022

~~For future visitors, the Jest + AsyncStorage integration moved to https://react-native-community.github.io/async-storage/docs/advanced/jest~~

The link changed again. See comment below.

Read more comments on GitHub >

github_iconTop Results From Across the Web

jest test fails after installing react-native-async-storage
But now I'm getting a new error. @RNCommunity/AsyncStorage: NativeModule.RCTAsyncStorage is null. I'm pasting the screenshot to show my project ...
Read more >
NativeModule: AsyncStorage is null when running jest - Reddit
I get this AsyncStorage is null when I'm writing tests. I have followed this link by adding mocks dir. https://react-native-async-storage.github ...
Read more >
ERROR Error: [@RNC/AsyncStorage]: NativeModule - Medium
ERROR Error: [@RNC/AsyncStorage]: NativeModule: AsyncStorage is null. Rebuild and restart the app. Run the packager with '--reset-cache' flag.
Read more >
Troubleshooting | Async Storage - GitHub Pages
This error means that AsyncStorage was unable to find its native module. This occurs because AsyncStorage was not linked into the final app...
Read more >
Encountered A Declaration Exception Jest React
Test encountered a declaration exception cannot run because stuff is. ... This function jest RNCAsyncStorage NativeModule AsyncStorage is null. Jest.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found