Expo Jest cannot find AsyncStorage even with mock dirctory or jest setup file - react-native

I am trying to include tests in my App created with Expo, but I am facing errors with AsyncStorage module
Could not find module '#react-native-async-storage/async-storage' from 'src/pages/Welcome.tsx'
I tested some configurations of the jest/expo to avoid this error, as downgrade the jest to version 26 as suggested in a GitHub issue of the project, using a mock directory as suggested here and in the official documentation here, and using jest setup file. Details below.
When I try with mock directory nothing changes in the error. The execution ignores the mock directory. When using the jest setup file the only change in the error message is that the message point to the jest setup file instead of the welcome.tsx.
The page tested is the "Welcome.tsx" that import the AsyncStorage
The test has nothing, only a a console log (code below) and don't use the AsyncStorage
The test code
const {getAllByTestId} = renderer.create(<Welcome />);
console.log(getAllByTestId);
The Welcome.tsx
...
<Image source=... testID="WelcomeImage" />
...
package.json
...
"scripts": { ... "test": "jest" ...},
"jest:" {
"preset": "jest-expo",
"globals": { "DEV": true
}
...
Installed versions
React: 17.0.1
React native: 0.64.3
React native testing library: 6.0.0
React test renderer: 17
Jest: 27.4.5

Follow the directions at - https://react-native-async-storage.github.io/async-storage/docs/advanced/jest/
Here is what I did:
Setup jestSetupFile.js as mentioned.
Setup mocks/#react-native-async-storage directory as mentioned
(I know it mentions to use either of two but I did both)
Cleared npm cache, deleted node-modules folder, deleted package-lock.json and did npm i again.(The usual steps to a clean start)
And it works now. Although I get error for enzyme but that is not within the scope of this question.

Related

Importing react-native package when running Vite

I am new to Vite and Vitest. I am experimenting a little bit, trying to add Vitest to a React-native app. I know Vite doesn't really support React Native but I would like to trying running just the tests with Vitest.
I get an error when trying to import React-native modules:
Module .../node_modules/react-native/index.js:14 seems to be an ES Module but shipped in a CommonJS package. You might want to create an issue to the package "react-native" asking them to ship the file in .mjs extension or add "type": "module" in their package.json.
As a temporary workaround you can try to inline the package by updating your config:
// vitest.config.js
export default {
test: {
deps: {
inline: [
"react-native"
]
}
}
}
When adding the suggested config the tests break inside React-native instead, as if the modules in fact is not supported.
What is going on here? Is React-Native only published as commonjs modules, while only esm-modules is supported by Vite? Is there a way around it?
Thanks in advance,
M.

Babel config only loaded once per reboot in React Native app?

I'm not quite sure what's going on here, but I have a React Native app that was ejected from Expo, with a babel.config.js defined, on Babel 7.9.0. I've thrown a console log in there to see if the config ever gets loaded, i.e.
module.exports = function (api) {
console.log('loading babel config!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
api.cache(true);
return {
presets: ['babel-preset-expo'],
};
};
But the console log only ever seems to print out once, and never again until I reboot my computer, even if I change the file, clear my yarn cache, or node_modules.
Actually, just figured it out: looks like I needed to clear the React Native cache itself before the config gets reloaded: yarn react-native start --reset-cache

Bundling a plugin with Rollup but having duplicate Vue.js package imported in the client app's bundle (Nuxt)

Dear Stack Overflow / Vue.js / Rollup community
This could be a noob question for the master plugin developers working with Vue and Rollup. I will write the question very explicitly hoping that it could help other noobs like me in the future.
I have simple plugin that helps with form validation. One of the components in this plugin imports Vue in order to programatically create a component and append to DOM on mount like below:
import Vue from 'vue'
import Notification from './Notification.vue' /* a very simple Vue component */
...
mounted() {
const NotificationClass = Vue.extend(Notification)
const notificationInstance = new NotificationClass({ propsData: { name: 'ABC' } })
notificationInstance.$mount('#something')
}
This works as expected, and this plugin is bundled using Rollup with a config like this:
import vue from 'rollup-plugin-vue'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
export default {
input: 'src/index.js',
output: {
name: 'forms',
globals: {
vue: 'Vue'
}
},
plugins: [
vue(),
babel(),
resolve(),
commonjs(),
terser()
],
external: ['vue']
}
As you can see, Vue.js is getting externalised in this bundle. The aim (and the assumption) is that the client app that imports this plugin will be running on Vue, therefore there's no need to bundle it here (assumption).
The very simple src/index.js that the bundler uses is below:
import Form from './Form.vue'
export default {
install(Vue, _) {
Vue.component('bs-form', Form)
}
}
Rollup creates 2 files (one esm and one umd) and references them in in the plugins package.json file like below:
"name": "bs-forms",
"main": "./dist/umd.js",
"module": "./dist/esm.js",
"files": [
"dist/*"
],
"scripts": {
"build": "npm run build:umd & npm run build:es",
"build:es": "rollup --config rollup.config.js --format es --file dist/esm.js",
"build:umd": "rollup --config rollup.config.js --format umd --file dist/umd.js"
}
Everything works as expected up to this point and the bundles are generated nicely.
The client app (Nuxt SSR) imports this plugin (using npm-link since it's in development) with a very simple import in a plugin file:
/* main.js*/
import Vue from 'vue'
import bsForms from 'bs-forms'
Vue.use(bsForms)
This plugin file (main.js) is added to nuxt.config.js as a plugin:
// Nuxt Plugins
...
plugins: [{src: '~/plugins/main'}]
...
Everything still works as expected but here comes the problem:
Since the clients is a Nuxt app, the Vue is imported by default of course but the externalised Vue module (by the forms plugin) is also imported in the client. Therefore there is a duplication of this package in the client bundle.
I guess the client app can configure its webpack config in order to remove this duplicated module. Perhaps by using something like a Dedupe plugin or something? Can someone suggests how to best handle situation like these?
But what I really want to learn, is the best practice of bundling the plugin at the first place, so that the client doesn't have to change anything in its config and simply imports this plugin and move on.
I know that importing the Vue.js in the plugin may not be a great thing to do at the first place. But there could be other reasons for an import like this as well, for example imagine that the plugin could be written in Typescript and Vue.js / Typescript is written by using Vue.extend statements (see below) which also imports Vue (in order to enable type interface):
import Vue from 'vue'
const Component = Vue.extend({
// type inference enabled
})
So here's the long question. Please masters of Rollup, help me and the community out by suggesting best practice approaches (or your approaches) to handle situations like these.
Thank you!!!!
I had the same problem and I found this answer of #vatson very helpful
Your problem is the combination of "npm link", the nature of nodejs module loading and the vue intolerance to multiple instances from different places.
Short introduction how import in nodejs works. If your script has some kind of library import, then nodejs initially looks in the local node_modules folder, if local node_modules doesn't contain required dependency then nodejs goes to the folder above to find node_modules and your imported dependency there.
You do not need to publish your package on NPM. It is enough if you generate your package locally using npm pack and then install it in your other project npm install /absolute_path_to_your_local_package/your_package_name.tgz. If you update something in your package, you can reinstall it in your other project and everything should work.
Here is the source about the difference between npm pack and npm link https://stackoverflow.com/a/50689049/6072503.
I have sorted this problem with an interesting caveat:
The duplicate Vue package doesn't get imported when the plugin is used via an NPM package (installed by npm install -save <plugin-name> )
However, during development, if you use the package vie npm link (like npm link <plugin-name>) then Vue gets imported twice, like shown in that image in the original question.
People who encounter similar problems in the future, please try to publish and import your package and see if it makes any difference.
Thank you!

Jest test __DEV__ is not defined

Basically my issue is that I get an error message, "__DEV__ is not defined" when I run jest. So I have read stackoverflow and other google posts on this. Some have suggested removing my .babelrc, but I actually need that file. Others have suggested adding
"globals": {
"__DEV__": true
}
To my package.json. I did that as well. I even deleted my node modules folder and re-installed. What should I do? Odd thing is that it was working before, but not now.
You can create a jest.config.json file in the root of your react-native project and add this globally as such
{
"jest": {
"globals": {
"__DEV__": true
}
}
}
Just add globals.DEV = true to your test file or set it in globals part of your jest settings
I got this when I was running Detox E2E tests inside of my react native app. Then use to work just fine but then I upgraded my mac OS and xcode and they started throwing Reference error DEV is not defined. Not sure why it was fine before and then broke after that.
My issue was fixed when I removed any code that was being imported from my react native app inside of the detox E2E tests. So the issue was importing any javascript from my app/ folder. I had a simple utility log function that wraps console.log which was the culprit. I did not need to modify any jest configs.
For anyone facing this issue I updated my jest by running in the terminal npm update jest this solved the issue for me.

Add dependencies to Aurelia project

I set up an Aurelia project using the minimal project given here.
Then I added the fetch-client using npm install aurelia-fetch-client --save command. It updated package.json to contain following:
"dependencies": {
"aurelia-fetch-client": "^1.1.0"
}
But when I added import {HttpClient} from 'aurelia-fetch-client'; to my app.js file and tried running the app, but got following error:
system.js:4 GET http://localhost:5000/aurelia-fetch-client 404 (Not Found)
How do I add that? Where does this project keep track of its dependencies? I have seen lots of tutorials which help setting up the fetch client in aurelia cli projects. How about the project given here?
First, follow Fabio Luz's advice above and actually install either aurelia-cli or a skeleton framework.
Then, I have found this next step to be one of the most common sources of confusion for most people who are learning Aurelia. After installing new modules via npm, you have to manually list them as a dependency in aurelia.json (in your aurelia_project folder). For example, you would list aurelia-fetch-client as follows:
"dependencies": [
"aurelia-binding",
"aurelia-bootstrapper",
"aurelia-dependency-injection",
"aurelia-event-aggregator",
...
"aurelia-fetch-client",
...
After it is listed as a dependency, it will be included in the vendor.js bundle (in the CLI, by running au run --watch) so that it can be accessed by your application when you import it in individual components.
import {HttpClient} from 'aurelia-fetch-client';
For me it worked like this (using the project generated by the CLI):
npm i whatwg-fetch --save
npm i aurelia-fetch-client --save
add "aurelia-fetch-client" to dependencies in aurelia_project/aurelia.json
example of app.js:
import {HttpClient} from 'aurelia-fetch-client';
let client = new HttpClient();
export class App{
activate(){
client.fetch('http://...json');
.then(response => response.json())
.then(data =>{
console.log(data)
});
}
}
You can also install dependencies with the CLI itself.
It doesn't always get it 100% correct but can point you in the right direction if struggling.
For example au install aurelia-fetch-client
It will download the dependency, add to packages.json and attempt to create an entry for the bundling.