I am trying to use a ValidationPipe but no matter how I write my code I get the following warning when sending a request: No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies.
My route looks something like this:
#Get()
#UsePipes(new ValidationPipe({ transform: true }))
async findAll(#Query() queryDto: QueryDto) {
return await this.myService.findAll(queryDto);
}
And my DTO looks something like this:
export class queryDto
{
#ApiModelProperty({
description: 'Maximum number of results',
type: Number,
example: 50,
default: 50,
required: false
})
readonly limit: number = 50;
}
I tried using the ValidationPipe several ways, following the doc, but nothing works for me. I know it does not work because although the request gets a response, the default value that I wrote in my DTO for the property limit, which is 50, is not used when the query is empty. Therefore, when no limit is provided in the query, limit's value is undefined, whereas it should be 50 (which means the ValidationPipe is not used).
My package.json seems correct:
npm ls class-validator
api-sport#0.0.1 /home/pierre_t/Bureau/dev/ApiSport
└── class-validator#0.9.1
Full package.json:
{
"name": "api-sport",
"version": "0.0.1",
"description": "",
"author": "",
"license": "MIT",
"scripts": {
"build": "tsc -p tsconfig.build.json",
"format": "prettier --write \"src/**/*.ts\"",
"start": "ts-node -r tsconfig-paths/register src/main.ts",
"start:dev": "nodemon",
"start:debug": "nodemon --config nodemon-debug.json",
"start:prod": "pm2 start ./src/main.js --no-daemon",
"lint": "tslint -p tsconfig.json -c tslint.json",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/common": "^6.0.5",
"#nestjs/core": "^6.0.5",
"#nestjs/platform-express": "^6.0.5",
"#nestjs/swagger": "^3.0.1",
"#nestjs/typeorm": "^6.0.0",
"#types/lodash": "^4.14.123",
"class-transformer": "^0.2.0",
"class-validator": "^0.9.1",
"dotenv": "^7.0.0",
"hbs": "^4.0.3",
"mysql": "^2.16.0",
"pm2": "^3.4.1",
"reflect-metadata": "^0.1.12",
"rimraf": "^2.6.2",
"rxjs": "^6.3.3",
"swagger-ui-express": "^4.0.2",
"typeorm": "^0.2.16"
},
"devDependencies": {
"#nestjs/testing": "^6.0.5",
"#types/express": "^4.16.0",
"#types/jest": "^23.3.13",
"#types/node": "^10.14.4",
"#types/supertest": "^2.0.7",
"jest": "^23.6.0",
"nodemon": "^1.18.9",
"prettier": "^1.15.3",
"supertest": "^3.4.1",
"ts-jest": "^23.10.5",
"ts-node": "^7.0.1",
"tsconfig-paths": "^3.7.0",
"tslint": "5.12.1",
"typescript": "^3.4.1"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
Why do I get this message and how can I use ValidationPipe?
This is because you are using class-validator but without any validations, see this issue:
Basically, it warns that you don't have any metadatas in the storage,
which means you haven't used any decorator from class-validator. That
means you don't perform any validation, so you should just pass
validate: false option to buildSchema to disable automatic validation.
I'm not sure if you can turn of validation for nest's ValidationPipe, but alternatively you can just add an assertion to your dto (if it makes sense), e.g.:
import { Min } from 'class-validator';
export class QueryDto {
#Min(1)
readonly limit: number = 50;
}
By the way: Since your #Query will only have string properties, you'll probably want to transform your limit from string to number. Have a look at this answer.
The question has already been answered, but for future reference of people with the same problem...
The class-validator allows you to bypass the validation of certain property (whitelisting) special flags to validate any property.
As the docs:
This will strip all properties that don't have any decorators. If no
other decorator is suitable for your property, you can use #Allow
decorator
e.g:
import {validate, Allow, Min} from "class-validator";
export class Post {
#Allow()
title: string;
#Min(0)
views: number;
nonWhitelistedProperty: number;
}
This is my bootstrap, it works with class-validator:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();
Related
I've a project with (next 12.1.6 + react 18.1 + react-dom 18.1). Now i want to add React Server Components to it. Updated my next.config.js like this
const nextConfig = {
distDir: '../../.next',
reactStrictMode: true,
experimental: {
runtime: 'nodejs',
serverComponents: true,
concurrentFeatures: true,
},
};
module.exports = nextConfig;
But regardless of that, when i execute npm run start:dev (npm run build works fine i believe) i get the error:
Error: `experimental.runtime` requires `experimental.reactRoot` to be enabled along with React 18. at Object.getBaseWebpackConfig [as default] (G:\ORLVNIcard\orlvni-business-card\node_modules\next\build\webpack-config.ts:355:11) at async Promise.all (index 0) at Span.traceAsyncFn (G:\ORLVNIcard\orlvni-business-card\node_modules\next\trace\trace.ts:106:14) at Span.traceAsyncFn (G:\ORLVNIcard\orlvni-business-card\node_modules\next\trace\trace.ts:106:14) at HotReloader.start (G:\ORLVNIcard\orlvni-business-card\node_modules\next\server\dev\hot-reloader.ts:518:21) at DevServer.prepare (G:\ORLVNIcard\orlvni-business-card\node_modules\next\server\dev\next-dev-server.ts:404:5) at ViewService.onModuleInit (G:\ORLVNIcard\orlvni-business-card\src\server\view\view.service.ts:19:7) at async Promise.all (index 0) at Object.callModuleInitHook (G:\ORLVNIcard\orlvni-business-card\node_modules\#nestjs\core\hooks\on-module-init.hook.js:43:5) at NestApplication.callInitHook (G:\ORLVNIcard\orlvni-business-card\node_modules\#nestjs\core\nest-application-context.js:169:13)
Next.js documentation says in https://nextjs.org/docs/advanced-features/react-18/server-components that i should use next#canary instead of next#12.1.6, and it works, but i have another problem with #canary in HookWebpackError: The "to" argument must be of type string. Received undefined and #12.1.6 does not throw the error in fresh barely empty project with (next 12.1.6 + react 18.1 + react-dom 18.1).
Part of my package.json looks like this
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build && cd src/client && next build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/common": "^8.0.0",
"#nestjs/config": "^1.1.5",
"#nestjs/core": "^8.0.0",
"#nestjs/jwt": "^8.0.0",
"#nestjs/mongoose": "^9.0.2",
"#nestjs/passport": "^8.0.1",
"#nestjs/platform-express": "^8.0.0",
"#types/bcrypt": "^5.0.0",
"#types/mongoose": "^5.11.97",
"bcrypt": "^5.0.1",
"cookie-parser": "^1.4.6",
"dotenv": "^10.0.0",
"mongodb": "^4.3.1",
"mongoose": "^6.1.10",
"mssql": "^7.3.0",
"next": "^12.1.6",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"react": "18.1.0",
"react-dom": "18.1.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"sass": "^1.45.0",
"ts-node": "^10.0.0"
},
"devDependencies": {
"#nestjs/cli": "^8.0.0",
"#nestjs/schematics": "^8.0.0",
"#nestjs/testing": "^8.0.0",
"#types/cookie-parser": "^1.4.2",
"#types/express": "^4.17.13",
"#types/jest": "27.0.2",
"#types/node": "^16.0.0",
"#types/passport-jwt": "^3.0.6",
"#types/react": "^18.0.12",
"#types/react-dom": "^18.0.5",
"#types/supertest": "^2.0.11",
"#typescript-eslint/eslint-plugin": "^5.0.0",
"#typescript-eslint/parser": "^5.0.0",
"eslint": "^7.28.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "^27.2.5",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "^27.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "^3.10.1",
"typescript": "^4.3.5"
},
And this is how i start my next app
import { Injectable, OnModuleInit } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import createServer from 'next';
import { NextServer } from 'next/dist/server/next';
import { Request, Response } from 'express';
#Injectable()
export class ViewService implements OnModuleInit {
private server: NextServer;
constructor(private configService: ConfigService) {}
async onModuleInit(): Promise<void> {
try {
this.server = createServer({
dev: this.configService.get<string>('NODE_ENV') !== 'production',
dir: './src/client',
});
await this.server.prepare();
} catch (error) {
console.error(error);
}
}
handler(req: Request, res: Response) {
return this.server.getRequestHandler()(req, res);
}
}
Guess the error is due to next somehow not seeing react 18 in #12.1.6, but i can't realize why, especially while in new project everything works fine.
Remove your package-lock.json and install the canary version of next
npm install next#canary react#latest react-dom#latest
Then add expermiental settings in your next.config.js
experimental: {
reactRoot: true,
runtime: "nodejs",
serverComponents: true,
concurrentFeatures: true
}
Apparently the error was thrown 'cause by default createServer() method of Next.js is creating react server with react 17 and old methods of react, like render(), hydrate() and so on. To make createServer() create react 18 server it's necessary to define __NEXT_REACT_ROOT as true in the environment of the process of our custom server. At least i've understood it this way. So the solution is
async onModuleInit(): Promise<void> {
process.env.__NEXT_REACT_ROOT = 'true';
try {
this.server = createServer({
dev: this.configService.get<string>('NODE_ENV') !== 'production',
dir: './src/client',
});
await this.server.prepare();
} catch (error) {
console.error(error);
}
}
It solved the problem for me.
Just add this line to your .env file and it will fix the issue
__NEXT_REACT_ROOT=true
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
I tried a lot to search for a solution to my problem all over the internet, however I couldn't find anything that could help me.
I have a JS utility file that allows me to test values.
Here is one of the functions that compose it :
const colorIsValid = (color) => {
if (!color || typeof color !== 'string') {
return false
}
if (CSS !== undefined) {
if (CSS.supports('color', color)) {
return true
}
throw new Error(`The provided color : "${color}" is not valid`)
}
throw new Error('Your navigator do not support CSS Api')
}
export { colorIsValid }
Everything works fine when I do a manual test on different browsers.
However when I run my tests with Jest I get the following error:
ReferenceError: CSS is not defined
here is my current environment.
// package.json
{
"name": "vue-polygon-grid",
"version": "1.0.0",
"description": "Interactive polygon structure for Vue.js",
"author": {
"name": "Guyomar Alexis",
"email": "contact#ag-dev.fr",
"url": "https://ag-dev.fr/"
},
"main": "dist/data-tables.min.js",
"homepage": "https://github.com/ga-devfront/vue-polygon-grid-private",
"keywords": [
"vue3",
"vuejs",
"vue",
"grid",
"polygon",
"composition"
],
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test": "jest"
},
"dependencies": {
"core-js": "^3.20.2",
"vue": "^3.0.0"
},
"devDependencies": {
"#babel/core": "^7.16.7",
"#babel/preset-env": "^7.16.8",
"#vue/cli-plugin-babel": "~4.5.15",
"#vue/cli-plugin-eslint": "~4.5.15",
"#vue/cli-service": "~4.5.15",
"#vue/compiler-sfc": "^3.2.26",
"#vue/eslint-config-airbnb": "^6.0.0",
"babel-eslint": "^10.1.0",
"babel-jest": "^27.4.6F",
"eslint": "^7.32.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jest": "^25.3.4",
"eslint-plugin-vue": "^8.2.0",
"jest": "27.4.7",
"jest-junit": "13.0.0",
"jest-transform-stub": "^2.0.0",
"sass": "^1.38.0",
"sass-loader": "^10"
}
}
// jest.config.js
module.exports = {
clearMocks: true,
collectCoverage: true,
coverageDirectory: 'coverage',
"collectCoverageFrom": [
"**/utility/*.{js,jsx}",
],
coverageReporters: ['html', 'text', 'text-summary', 'cobertura'],
transform: {
'^.+\\.js$': 'babel-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|jpeg|svg|ttf|woff|woff2)$': 'jest-transform-stub',
},
reporters: [
'default',
['jest-junit', { outputDirectory: 'coverage' }],
],
};
Does anyone have a solution so I can test my methods?
Thank you in advance for taking the time to read me.
jest runs via Node runtime, meaning there are no browser APIs. You will need to mock it. Look into jest setupFiles.
Create a setup file:
global.CSS = {
supports: (k, v) => false,
}
Then use that setup file to add CSS object onto global object.
This answer might also be helpful.
If you really must have DOM APIs you can include package JSDOM that can help. In my opinion in most cases it’s unnecessary dependency.
From your question it sounds like you just need your tests to run. Do you really need to set up global CSS object? Are you sure you’re not testing implementation details?
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.
I just started using Ember. I already had some trouble with the Ember Quickstart tutorial which describes that hbs and js files for components should both be put in app/components. The only way it works on my machine is with the js file in app/components, but the hbs file in app/templates/components. That's also what ember generate component people-list did.
Now, there's another problem: The first line in people-list.js is
import Component from '#glimmer/component';
This causes the error Could not find module #glimmer/component imported from ember-quickstart/components/people-list. There is no build error, but the component's content does not render. What can I do about this?
edit 1: In my other question, Ember Octane was mentioned. This is the output of ember -v:
ember-cli: 3.18.0
node: 11.13.0
os: darwin x64
edit 2 Below is my package.json after adding glimmer. I could run npm install, but yarn install gives me The engine "node" is incompatible with this module. Expected version "10.* || >= 12". Got "11.13.0".
{
"name": "ember-quickstart",
"version": "0.0.0",
"private": true,
"description": "Small description for ember-quickstart goes here",
"repository": "",
"license": "MIT",
"author": "",
"directories": {
"doc": "doc",
"test": "tests"
},
"scripts": {
"build": "ember build",
"lint:hbs": "ember-template-lint .",
"lint:js": "eslint .",
"start": "ember serve",
"test": "ember test"
},
"devDependencies": {
"#ember/jquery": "^0.5.2",
"#ember/optional-features": "^0.6.3",
"broccoli-asset-rev": "^2.7.0",
"ember-ajax": "^5.0.0",
"ember-cli-app-version": "^3.2.0",
"ember-cli-babel": "^7.1.2",
"ember-cli-dependency-checker": "^3.1.0",
"ember-cli-eslint": "^4.2.3",
"ember-cli-htmlbars": "^3.0.0",
"ember-cli-htmlbars-inline-precompile": "^1.0.3",
"ember-cli-inject-live-reload": "^1.8.2",
"ember-cli-sri": "^2.1.1",
"ember-cli-template-lint": "^1.0.0-beta.1",
"ember-cli-uglify": "^2.1.0",
"ember-data": "~3.9.0",
"ember-export-application-global": "^2.0.0",
"ember-load-initializers": "^1.1.0",
"ember-maybe-import-regenerator": "^0.1.6",
"ember-qunit": "^3.4.1",
"ember-resolver": "^5.0.1",
"ember-source": "~3.9.0",
"ember-welcome-page": "^3.2.0",
"eslint-plugin-ember": "^5.2.0",
"loader.js": "^4.7.0",
"qunit-dom": "^0.8.0"
},
"engines": {
"node": "10.* || >= 12"
},
"dependencies": {
"ember-cli": "^3.18.0",
"#glimmer/component": "^1.0.0"
}
}
Now the problem described above is gone, instead I get Parsing error: Unexpected character '#' in line 5 of people-list.js:
import Component from '#glimmer/component';
import { action } from '#ember/object';
export default class PeopleListComponent extends Component {
#action
showPerson(person) {
alert(`The person's name is ${person}!`);
}
}
Please ensure that "#glimmer/component": "^1.0.0" line exists in your package.json. Then rerun npm install or yarn install and restart ember s. This should be there if you had used ember new with Ember 3.14+, but it seems like it might be missing.