Reputation:
When I run npm test
:
➜ mobile git:(develop) ✗ npm test
> jest
FAIL __tests__/index.js
● Test suite failed to run
TypeError: Cannot read property 'fs' of undefined
at Object.<anonymous> (node_modules/react-native-cached-image/utils/fsUtils.js:9:12)
at Object.<anonymous> (node_modules/react-native-cached-image/ImageCacheManager.js:5:13)
at Object.<anonymous> (node_modules/react-native-cached-image/CachedImage.js:13:23)
I see it's related to react-native-cached-image
dependency on fs
.
Do I have to mock fs somehow? I tried couple of things but wasn't successful.
Upvotes: 0
Views: 2393
Reputation: 1593
Mocking components using fs
Instead of mocking fs I would recommend you to mock react-native-image-cache if possible because fs is used by one of the dependencies of that package. You can see the line listed in you're error.
You can just mock react-native-image-cache like the following:
jest.mock('react-native-img-cache', () => {
return {
DocumentDir: () => {},
ImageCache: {
get: {
clear: () => {}
}
}
}
})
In the same matter it should be possible to mock react-native-fetch-blob which is using fs and causing the error. The properties on the return statement depend on the methods and properties that are used by image-cache lib. Probably you don't need as much as listed below but now you know that there could be more than fs.
jest.mock('react-native-fetch-blob', () => {
return {
DocumentDir: () => {},
fetch: () => {},
base64: () => {},
android: () => {},
ios: () => {},
config: () => {},
session: () => {},
fs: {
dirs: {
MainBundleDir: () => {},
CacheDir: () => {},
DocumentDir: () => {},
},
},
wrap: () => {},
polyfill: () => {},
JSONStream: () => {}
}
})
Mocking fs
In case you want/need to mock fs specifically, you could do the following:
Sometimes it's even possible to do something like that:
fs = require("fs")
fs.readFile = function (filename, cb) {
cb(null, new Buffer("fake contents");
};
// etc
But keep in mind that fs is used somewhere in an dependent package. In that case I'm not sure if the code works properly and this is why I put the other options at the top.
Upvotes: 4