Getting Error When Using Next.js With Jest - javascript

I am trying to run a test in next.js using jest, but i keep getting an error:
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.
I have tried following the link and addding the docblock:
/**
* #jest-environment jsdom
*/
to my code with no success.
I have also tried configuring my jest.config.js based on the next.js testing page. This does not work I have tried both the solution with and without the rust compiler. Neither works:
Package.JSON:
{
"name": "chat",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"test": "jest --env=node --forceExit --watchAll --coverage"
},
"dependencies": {
"#firebase/testing": "^0.20.11",
"firebase": "^9.9.4",
"kill-port": "^2.0.1",
"next": "12.2.5",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-firebase-hooks": "^5.0.3",
"react-hot-toast": "^2.3.0",
"uuid": "^8.3.2"
},
"devDependencies": {
"#babel/plugin-syntax-jsx": "^7.18.6",
"#babel/preset-react": "^7.18.6",
"#firebase/rules-unit-testing": "^2.0.4",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#types/jest": "^29.0.2",
"eslint": "8.23.0",
"eslint-config-next": "12.2.5",
"firebase-admin": "^11.0.1",
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3"
}
}
Jest.config.js:
// jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
/** #type {import('jest').Config} */
const customJestConfig = {
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
//moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
test/page.test.js
import { render, screen } from '#testing-library/react';
import Home from '../pages/index';
describe('Home', () => {
it('renders a heading', () => {
render(<Home />);
expect(2 + 2).toBe(4);
});
});

You're overriding the env in your npm test script, remove --env=node:
"test": "jest --forceExit --watchAll --coverage"

Related

Turborepo: Unable to resolve "expo" from "index.ts"

I'm trying to run expo on a turborepo.
Running pnpm dev gives me the following error:
Unable to resolve "expo" from "index.ts"
And the simulator the following screen with the following error:
Unable to resolve module expo from /Users/xx/main/apps/expo/index.ts: expo could not be found within the project or in these directories:
node_modules
../../node_modules
> 1 | import { registerRootComponent } from "expo";
| ^
2 |
3 | import { App } from "./src/_app";
4 |
I have tried to delete all my node_modules.
I have tried to clean my entire project.
I have no idea what to do next.
Here is my metro.config.js:
// Learn more: https://docs.expo.dev/guides/monorepos/
const { getDefaultConfig } = require("expo/metro-config");
const path = require("path");
const projectRoot = __dirname;
const workspaceRoot = path.resolve(projectRoot, "../..");
// Create the default Metro config
const config = getDefaultConfig(projectRoot);
// Add the additional `cjs` extension to the resolver
config.resolver.sourceExts.push("cjs");
// 1. Watch all files within the monorepo
config.watchFolders = [workspaceRoot];
// 2. Let Metro know where to resolve packages and in what order
config.resolver.nodeModulesPaths = [
path.resolve(projectRoot, "node_modules"),
path.resolve(workspaceRoot, "node_modules"),
];
// 3. Force Metro to resolve (sub)dependencies only from the `nodeModulesPaths`
config.resolver.disableHierarchicalLookup = true;
module.exports = config;
Here is my package.json:
{
"name": "#acme/expo",
"version": "0.1.0",
"main": "index.ts",
"scripts": {
"clean": "rm -rf .expo .turbo node_modules",
"dev": "expo start --ios",
"dev:android": "expo start --android",
"dev:ios": "expo start --ios",
"lint": "eslint",
"type-check": "tsc --noEmit"
},
"dependencies": {
"expo": "~47.0.12",
"expo-status-bar": "~1.4.2",
"react": "18.1.0",
"react-dom": "18.1.0",
"react-native": "0.70.5",
"react-native-safe-area-context": "4.4.1",
"expo-splash-screen": "~0.17.5"
},
"devDependencies": {
"#babel/core": "^7.19.3",
"#babel/preset-env": "^7.19.3",
"#babel/runtime": "^7.19.0",
"#expo/config-plugins": "^5.0.4",
"#types/react": "^18.0.25",
"#types/react-native": "~0.70.8",
"eslint": "^8.30.0",
"typescript": "^4.9.4"
},
"private": true
}
Thanks you for helping.
I couldn't get it working with pnpm (I tried for way too long), so I switched over to yarn 1 (classic) workspaces and it worked. Yarn 1 workspaces are the only workspace solution that Expo supports, so I recommend going with that.

Nuxt-ts, vuex error: This dependency was not found in .nuxt/store.js

OS: Windows 10
what am I already did
Delete .nuxt and run "yarn run dev": not work
Delete .nuxt and run "npm run dev": not work
Change node version to 16.15.1 and 14.19.3: not work
Team Repository, can not recreate the project.
I think because nuxtJS generate .nuxt/store.js with double back slash
but I can not force nuxtJS to use forward slash
ERROR Failed to compile with 1 errors friendly-errors 15:27:35
This dependency was not found: friendly-errors 15:27:35
friendly-errors 15:27:35
* ..\store\signIn.ts in ./.nuxt/store.js
/.nuxt/store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const VUEX_PROPERTIES = ["state", "getters", "actions", "mutations"];
let store = {};
(function updateModules() {
store = normalizeRoot(require("..\\store\\index.ts"), "store/index.ts");
// If store is an exported method = classic mode (deprecated)
if (typeof store === "function") {
return console.warn(
"Classic mode for store/ is deprecated and will be removed in Nuxt 3."
);
}
// Enforce store modules
store.modules = store.modules || {};
resolveStoreModules(require("..\\store\\auth.ts"), "auth.ts");
resolveStoreModules(require("..\\store\\profile.ts"), "profile.ts");
resolveStoreModules(require("..\\store\\signIn.ts"), "signIn.ts");
I don't know why it passes all require() to error at "..\store\signIn.ts"
/store/index.js
export const state = () => ({})
export const getters = {}
export const mutations = {}
export const actions = {}
/store/signIn.js
// /store/signIn.ts
import { getterTree, mutationTree, actionTree } from 'typed-vuex'
package.json
{
"name": "nuxt-web",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt-ts",
"build": "nuxt-ts build",
"generate": "nuxt-ts generate",
"start": "nuxt-ts start",
"lint": "eslint --ext .ts,.js,.vue .",
"lint:js": "eslint --ext \".js,.ts,.vue\" --ignore-path .gitignore .",
"lintfix": "npm run lint:js -- --fix"
},
"dependencies": {
"#nuxt/typescript-runtime": "^2.1.0",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/dotenv": "^1.4.1",
"bootstrap": "^4.6.1",
"bootstrap-vue": "^2.21.2",
"core-js": "^3.19.3",
"nuxt": "^2.15.8",
"nuxt-property-decorator": "^2.9.1",
"nuxt-typed-vuex": "^0.3.0",
"nuxt-web3": "^0.0.8",
"vue": "^2.6.14",
"vue-class-component": "^7.2.6",
"vue-server-renderer": "^2.6.14",
"vue-template-compiler": "^2.6.14",
"webpack": "^4.46.0"
},
"devDependencies": {
"#babel/eslint-parser": "^7.16.3",
"#nuxt/types": "^2.15.8",
"#nuxt/typescript-build": "^2.1.0",
"#nuxtjs/eslint-config-typescript": "^8.0.0",
"#nuxtjs/eslint-module": "^3.0.2",
"#nuxtjs/vercel-builder": "^0.21.3",
"#types/vuelidate": "^0.7.15",
"eslint": "^8.4.1",
"eslint-plugin-nuxt": "^3.1.0",
"eslint-plugin-vue": "^8.2.0",
"typescript": "^4.6.3",
"vuelidate": "^0.7.7"
}
}
it's my first question, apologies if it unclear
The issue got resolved after doing this
change node version to 12.17.0
remove .next
remove node_modules
npm install
npm run dev

Jest - ReferenceError: __DEV__ is not defined (React Native)

I am trying to get jest to work with a new react-native project. However, when I run npm run test, I get the following error ReferenceError: __DEV__ is not defined. I've looked through countless Github issues and Stack Overflow posts regarding this but none of the suggestions have worked in my case.
Here is my jest.config.js file:
module.exports = {
transformIgnorePatterns: [
"node_modules/(?!(react-native|react-native-button|react-native-video)/)"
],
setupFiles: ['<rootDir>/__tests__/setup.json'],
}
package.json (notice I added DEV = true inside "jest")
{
"name": "DigitalSignagePlayer",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#react-native-async-storage/async-storage": "^1.15.5",
"axios": "^0.21.1",
"react": "^17.0.1",
"react-native": "0.64.2",
"react-native-fs": "^2.18.0",
"react-native-splash-screen": "^3.2.0",
"react-native-video": "^5.1.1"
},
"devDependencies": {
"#babel/core": "^7.14.5",
"#babel/preset-env": "^7.14.7",
"#babel/runtime": "^7.14.5",
"#react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^27.0.2",
"eslint": "^7.28.0",
"jest": "^27.0.5",
"metro-react-native-babel-preset": "^0.66.0",
"react-test-renderer": "17.0.1"
},
"jest": {
"preset": "react-native",
}
}
bable.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset', '#babel/preset-env'],
};
metro.config.js
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* #format
*/
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
I have tried setting globals.DEV = true and global.DEV = true at the top of my test files. I have tried adding setupFiles to jest.config.js which loads a setup.js file that contains global.DEV = true too. I have tried updating jest also. My current version of react-native is:
react-native-cli: 2.0.1
react-native: 0.64.2
I'm also using Metro, not Expo and I initially created the app with react-native-cli.
UPDATE:
setup.json
{
"globals": { "__DEV__": true }
}
UPDATE 2:
I changed setup.json to setup.js but I am still getting the same error:
global.__DEV__ = true
The variable is called __DEV__, so using DEV by trial and error doesn't make sense. Setting it in tests won't help because it won't affect the usage of the variable on import. In order to do this, this should have been done before tests in setupFiles* files.
Jes globals configuration option is supposed to do this. There should be "globals": { "__DEV__": true }. The configuration in package.json overridden by the configuration in jest.config.js. There should be only one of them (likely the latter), the other one needs to be removed.

deploy nextjs app on firebase google cloud

I am thinking of deploying nextjs project on gcp firebase. However, I could not see any pages running. I mean it's shown fully blank. I am not quite sure if I missed something for deployment.
Here is my configuration
.next
public
src
pages
components
assets - images
server.js
.babelrc
.env.development
.env.staging
.env.production
.firebaserc
firebase.json
jsconfig.json
next.config.js
Now the setup for deployment
firebase.json
{
"hosting": {
"public": "public",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**/**",
"function": "next"
}
]
},
"functions": {
"source": ".",
"ignore": [
".firebase/**",
".firebaserc",
"firebase.json",
"**/node_modules/**",
"**/.vscode/**",
"**/conventions/**",
"**/.hooks/**",
"**/public/**"
]
}
}
.firebaserc
{
"projects": {
"default": "jeweltrek-test"
}
}
next.config.js
const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");
const withPWA = require("next-pwa");
module.exports = withPlugins(
[optimizedImages],
[
withPWA({
pwa: {
dest: "public",
},
}),
]
);
server.js
const functions = require('firebase-functions');
const next = require('next');
var dev = process.env.NODE_ENV !== 'production';
var app = next({ dev, conf: { distDir: '.next' } });
var handle = app.getRequestHandler();
exports.next = functions.https.onRequest((req, res) => {
console.log('File: ' + req.originalUrl); // log the page.js file that is being requested
return app.prepare().then(() => handle(req, res));
});
package.json
{
"name": "jeweltrek-next",
"version": "0.1.0",
"private": true,
"main": "server.js",
"engines": {
"node": "10"
},
"scripts": {
"dev:client": "next",
"dev:server": "node src/server --source-maps --watch",
"dev": "dotenv -e .env.development yarn dev:client & yarn dev:server",
"build": "dotenv -e .env.production next build",
"build:staging": "dotenv -e .env.staging next build",
"serve": "dotenv -e .env.staging firebase serve --only functions,hosting",
"deploy": "dotenv -e .env.staging firebase deploy --only functions,hosting",
"start": "next start"
},
"dependencies": {
"apollo-boost": "^0.4.7",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"firebase-admin": "^8.12.1",
"firebase-functions": "^3.6.1",
"formik": "^2.1.4",
"graphql": "^15.0.0",
"html-to-draftjs": "^1.5.0",
"imagemin-mozjpeg": "^8.0.0",
"imagemin-optipng": "^7.1.0",
"isomorphic-fetch": "^2.2.1",
"isomorphic-unfetch": "^3.0.0",
"lodash": "^4.17.15",
"lqip-loader": "^2.2.0",
"next": "^9.4.0",
"next-compose-plugins": "^2.2.0",
"next-optimized-images": "^2.5.8",
"next-pwa": "^2.4.1",
"next-runtime-dotenv": "^1.2.0",
"nprogress": "^0.2.0",
"react": "16.13.1",
"react-apollo": "^3.1.5",
"react-apollo-hooks": "^0.5.0",
"react-dom": "16.13.1",
"react-draft-wysiwyg": "^1.14.4",
"styled-components": "^5.1.0",
"webp-loader": "^0.6.0",
"yup": "^0.28.3"
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"firebase-functions-test": "^0.2.1"
}
}
for deploying what I am doing is
First i build file using yarn build:staging if its for staging
yarn deploy
it says deployment complete as well with no error but if i navigate to the browser then it does not render the pages
https://us-central1-jeweltrek-test.cloudfunctions.net/next/
this is what i get
It could be something related to permissions to cloud functions and IAM or authentication, check this page: https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
Also, check this answer:
Firebase Functions HTTPS 403 Forbidden
I hope this solves it. Good Luck!

Google App Engine: Modify Cloud Run Environment

I'm trying to deploy a Next.js app which uses a custom Node.js server.
I want to inject custom build variables into the app:
next.config.js
const NODE_ENV = process.env.NODE_ENV;
const envType = NODE_ENV === `production` ? `production` : `staging`;
const envPath = `./config/${envType}`;
const { env } = require(envPath);
module.exports = {
env: { ...env },
};
The above file is run at build time (yarn build).
The issue is that Google App Engine uses Cloud Build behind the scenes. There, the NODE_ENV is always set to development. How can I override the NODE_ENV there; i.e. how can I customize the Cloud Build used for the Google App Engine gcloud app deploy?
I can't just use Docker because of this issue.
package.json
{
"name": "blah",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "NODE_ENV=staging node server.js",
"build": "rm -rf node_modules/ && yarn && rm -rf .next/ && next build",
"start": "node server.js",
"lint": "eslint . --ext .js",
"gcp-build": "yarn build"
},
"dependencies": {
"body-parser": "^1.18.3",
"dotenv": "^7.0.0",
"dotenv-webpack": "^1.7.0",
"express": "^4.16.4",
"express-session": "^1.16.1",
"firebase": "^5.10.0",
"firebase-admin": "^7.3.0",
"isomorphic-unfetch": "^3.0.0",
"lodash": "^4.17.11",
"next": "^8.1.0",
"now": "^15.0.6",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"session-file-store": "^1.2.0",
"styled-components": "^4.2.0",
"yenv": "^2.1.0"
},
"devDependencies": {
"babel-eslint": "^10.0.1",
"eslint": "^5.16.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.17.2",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.12.4"
},
"engines": {
"node": "10.x.x"
}
}
app.yaml
runtime: nodejs10
image
Below is the output of passing a DOGE_ENV variable from app.yaml. As you can see, it is undefined. However, NODE_ENV is development.
That is, adding the following to app.yaml does not work.
env_variables:
DOGE_ENV: production
Don't use NODE_ENV, create your own environment variable and use that:
App.yaml
env_variables:
ST_ENV: Production
next.config.js
const environment = process.env.ST_ENV;
const envType = environment === `production` ? `production` : `staging`;
const envPath = `./config/${envType}`;
const { env } = require(envPath);
module.exports = {
env: { ...env },
};
I had the same issue, at the end I solved setting NODE_ENV=production in the package.json script, so in your case just use:
{
"gcp-build": "NODE_ENV=production yarn build"
}
otherwise you can create a Cloud Build configuration file, check the docs, it supports an env section where you can define environmental variables
I had the same problem and ended up using an approach similar to Luca's answer, but with a mechanism to substitute the correct variable in package.json before the deploy (using the microsoft/variable-substitution GitHub action in my case).

Categories

Resources