Skip to content
This repository has been archived by the owner on Mar 16, 2019. It is now read-only.

How to test code that depends on RNFetchBlob #212

Open
neiker opened this issue Dec 11, 2016 · 24 comments
Open

How to test code that depends on RNFetchBlob #212

neiker opened this issue Dec 11, 2016 · 24 comments

Comments

@neiker
Copy link

neiker commented Dec 11, 2016

If I want to test a module and that module includes RNFetchBlob, I get this:
react-native-fetch-blob/index.js:6 import { ^^^^^^ SyntaxError: Unexpected token import

That's because babel-core/register don't transpire code within node_modules by default. It I change the config to do it, as it's mentioned here, it crash in this line because NativeModules.RNFetchBlob it's undefined. I get stuck there so I change my es6 include to this dirty piece of code:

let RNFetchBlob;
if (process.env.NODE_ENV !== 'test') {
  // eslint-disable-next-line global-require
  RNFetchBlob = require('react-native-fetch-blob').default;
}

Any ideas how to solve this?

This is my test script:
NODE_ENV='test' mocha 'app/**/__tests__/*.js' --compilers js:babel-core/register --require mocha_setup.js

@layik
Copy link

layik commented Dec 13, 2016

I am using Facebook's Jest and I get the same error.

    TypeError: Cannot read property 'DocumentDir' of undefined
      
      at Object.<anonymous> (node_modules/react-native-fetch-blob/fs.js:25:24)
      at Object.<anonymous> (node_modules/react-native-fetch-blob/index.js:20:9)

I did try mocking the module, but then I use a constant Blob from RNFetchBlob.polyfill.Blob that then fails the test as it will be "undefined".

Thanks.

@ohtangza
Copy link

I am also experiencing the same error; "TypeError: Cannot read property 'DocumentDir' of undefined"

@rahimrahman
Copy link

rahimrahman commented Jan 31, 2017

@neiker @layik @ohtangza have you guys been able to remedy this issue? I'm having the same issue.

cc: @wkh237

@neiker
Copy link
Author

neiker commented Jan 31, 2017

@rahimrahman nop, I just include RNFB conditionally based on NODE_ENV

@jnrepo
Copy link

jnrepo commented May 8, 2017

You have to mock the library. Was using the react-native-img-cache library which had a dependency to react-native-fetch-blob, so my jest is mocking that module.

EX:

jest.mock('react-native-img-cache', () => {
  return {
    DocumentDir: () => {},
    ImageCache: {
      get: {
        clear: () => {}
      }
    }
  }
})

@leyuan
Copy link

leyuan commented Jun 13, 2017

Agreed with @jnrepo, the key is to mock the objects you are accessing in your code, code work for me

jest.mock('react-native-fetch-blob', () => {
  return {
    DocumentDir: () => {},
    polyfill: () => {},
  }
});

@scerelli
Copy link

scerelli commented Jul 10, 2017

I created a file inside the __mocks__ folder called react-native-fetch-blob.js and i mocked all the keys this way:

jest.mock('react-native-fetch-blob', () => {
  return {
    DocumentDir: () => {},
    fetch: () => {},
    base64: () => {},
    android: () => {},
    ios: () => {},
    config: () => {},
    session: () => {},
    fs: () => {},
    wrap: () => {},
    polyfill: () => {},
    JSONStream: () => {}
  };
});

but i still get an error related to the dir constants:
TypeError: Cannot read property 'dirs' of undefined

any idea?

@SoundBlaster
Copy link

@scerelli try this

  return {
    DocumentDir: () => {},
    fetch: () => {},
    base64: () => {},
    android: () => {},
    ios: () => {},
    config: () => {},
    session: () => {},
    fs: {
      dirs: {
        MainBundleDir: () => {},
        CacheDir: () => {},
        DocumentDir: () => {},
      },
    },
    wrap: () => {},
    polyfill: () => {},
    JSONStream: () => {}
  }
})```

@scerelli
Copy link

thx @SoundBlaster but this doesn't solve the error.

@aofeng2009
Copy link

aofeng2009 commented Jul 27, 2017

+1,After reinstall, delete app,restart, also failed.

edit
When I make another configuration in my Podfile. Now everything is ok.

@jnrepo
Copy link

jnrepo commented Jul 27, 2017

@scerelli mines setup this way

in package.json:

"jest": {
    "preset": "react-native",
    "setupFiles": [
      "./test/setup.js"
    ],
    "coveragePathIgnorePatterns": [
      "/test/"
    ],
    "moduleFileExtensions": [
      "js",
      "json"
    ]
  }

in test/setup.js:

jest.mock('react-native-img-cache', () => {
  return {
    DocumentDir: () => {},
    ImageCache: {
      get: {
        clear: () => {}
      }
    }
  }
})

react-native-img-cache was the module using the react-native-fetch-blob. Perhaps its not react-native-fetch-blob, but another module thats using it?

@scerelli
Copy link

@jnrepo look this is the fetch-blob mocked log and this is the jest error:

https://cl.ly/3E3C242g1M1K

and the line raising this error is:

 const config = {
      overwrite : false,
      path: `${RNFetchBlob.fs.dirs.DocumentDir}/videos`,
      fileCache
    };

@jasongaare
Copy link

I'm doing all the mocks correctly, AFAIK, but this is the error I get:

Test suite failed to run

ReferenceError: self is not defined
  
  at node_modules/react-native-fetch-blob/lib/oboe-browser.min.js:1:12597
  at Object.<anonymous> (node_modules/react-native-fetch-blob/lib/oboe-browser.min.js:1:12611)
  at Object.<anonymous> (node_modules/react-native-fetch-blob/json-stream.js:1:391)
  at Object.<anonymous> (node_modules/react-native-fetch-blob/index.js:28:17)

Seems to be something with the minified oboe code... any idea how to resolve that one?

@lll000111
Copy link
Contributor

lll000111 commented Aug 31, 2017

https://github.com/wkh237/react-native-fetch-blob/blob/master/lib/oboe-browser.js#L2701

It indeed is not defined, the line where it is used is the only line where it is mentioned. // cc @wkh237

Is it supposed to be this property? https://developer.mozilla.org/en/docs/Web/API/Window/self

@wkh237
Copy link
Owner

wkh237 commented Aug 31, 2017

Does it help if you add this line at the beginning of your program ?

global.self = {}

@lll000111
Copy link
Contributor

lll000111 commented Aug 31, 2017

@lll000111
Copy link
Contributor

@wkh237 Actually, I think we need to include this, since it's RNFB code that uses self. It doesn't exist in RN, it seems.

@lll000111 lll000111 added the task label Sep 3, 2017
@jasongaare
Copy link

@wkh237 @lll000111

Sorry just circling back to this... adding global.self = {} does allow my tests to run! I'm going to run with that solution for the timebeing

@maldimirov
Copy link

As @scerelli I also wanted the mock to happen in a separate place so it can be used by all tests. Placing the following code in <project_root>/__mocks__/react-native-fetch-blob.js seems to work for me:

const existsMock = jest.fn();
existsMock.mockReturnValueOnce({then: jest.fn()});

export default {
    DocumentDir: () => {},
    ImageCache: {
        get: {
            clear: () => {},
        },
    },
    fs: {
        exists: existsMock,
        dirs: {
            MainBundleDir: () => {},
            CacheDir: () => {},
            DocumentDir: () => {},
        },
    },
};

It's a variation of @SoundBlaster solution, just in a global mock file. With that I don't need to import or implicitly mock anything in the test code.

@ThaJay
Copy link

ThaJay commented Dec 1, 2017

for me this object works as mock

jest.mock('react-native-fetch-blob', () => {
  return {
    fs: {
      dirs: {
        DocumentDir: ''
      },
      writeFile: () => Promise.resolve()
    }
  }
})

@mikeevstropov
Copy link

Hi. If someone still get an error

/node_modules/redux-persist-filesystem-storage/index.js:5
import RNFetchBlob from 'react-native-fetch-blob'
^^^^^^    
SyntaxError: Unexpected token import

just add into "jest" section of package.json following option

"transformIgnorePatterns": [
  "node_modules/(?!react-native|react-navigation)/"
]

@anhnguyenvan-agilityio
Copy link

@maldimirov thanks your solution, you save my life ! 💯

@linnett
Copy link

linnett commented Oct 3, 2018

The jest.mock should be added to documentation. Really useful

@indapublic
Copy link

@maldimirov You are awesome!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests