truong thanh
truong thanh

Reputation: 61

Fail to run Jest unit test in react-native with react-native-fs lib

I create a new react-native app with the latest version, the default testing works well. Then I use 'react-native-fs' lib to write a file in my app and it works fine. But I try to run the testing command, it failed.

> [email protected] test D:\test\TestJest
> jest

 FAIL  __tests__\index.android.js
  ● Test suite failed to run

TypeError: Cannot read property 'RNFSFileTypeRegular' of undefined

  at Object.<anonymous> (node_modules\react-native-fs\FS.common.js:17:36)
  at Object.<anonymous> (index.android.js:14:20)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.8s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

I have followed the manual document of Jest but I haven't resolved error yet. Here is my example repo. Could you have a look at my example repo and let me know what I wrong?

Thank you.

Upvotes: 6

Views: 4540

Answers (1)

Francois Nadeau
Francois Nadeau

Reputation: 7463

For those looking for a quick solution for this problem:

Create a file named react-native-fs.js inside your __mocks__ folder, and add this as its content:

jest.mock('react-native-fs', () => {
  return {
    mkdir: jest.fn(),
    moveFile: jest.fn(),
    copyFile: jest.fn(),
    pathForBundle: jest.fn(),
    pathForGroup: jest.fn(),
    getFSInfo: jest.fn(),
    getAllExternalFilesDirs: jest.fn(),
    unlink: jest.fn(),
    exists: jest.fn(),
    stopDownload: jest.fn(),
    resumeDownload: jest.fn(),
    isResumable: jest.fn(),
    stopUpload: jest.fn(),
    completeHandlerIOS: jest.fn(),
    readDir: jest.fn(),
    readDirAssets: jest.fn(),
    existsAssets: jest.fn(),
    readdir: jest.fn(),
    setReadable: jest.fn(),
    stat: jest.fn(),
    readFile: jest.fn(),
    read: jest.fn(),
    readFileAssets: jest.fn(),
    hash: jest.fn(),
    copyFileAssets: jest.fn(),
    copyFileAssetsIOS: jest.fn(),
    copyAssetsVideoIOS: jest.fn(),
    writeFile: jest.fn(),
    appendFile: jest.fn(),
    write: jest.fn(),
    downloadFile: jest.fn(),
    uploadFiles: jest.fn(),
    touch: jest.fn(),
    MainBundlePath: jest.fn(),
    CachesDirectoryPath: jest.fn(),
    DocumentDirectoryPath: jest.fn(),
    ExternalDirectoryPath: jest.fn(),
    ExternalStorageDirectoryPath: jest.fn(),
    TemporaryDirectoryPath: jest.fn(),
    LibraryDirectoryPath: jest.fn(),
    PicturesDirectoryPath: jest.fn(),
  };
});

Enjoy!

Upvotes: 15

Related Questions