CSS.supports is not defined in Jest test - javascript

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?

Related

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.

Property 'noise' does not exist on type 'typeof #types/p5/index"'

I was humming along in a TypeScript Data Viz project and thought I'd use the p5.js noise function to save some time. Instead I've encountered a problem that I can't fully understand. There seems to be something different with the p5 module compared to d3 and three.js I'm using in the project. Breaking it down to the very basic elements, I need some help interpreting what's going on with this module.
import * as p5 from "p5"
p5.noise()
// Returns the error:
// Property 'noise' does not exist on type 'typeof import("/Users/.../ts-node-server/node_modules/#types/p5/index.d.ts")'. ts(2339)
If I try to use the function directly I get a different error.
import { noise } from "p5"
// Returns the error:
// Module '"p5"' has no exported member 'noise'.ts(2305)
I dug down into the node_modules and confirmed everything is there. Researching the problem, I noticed other packages had this same error, but all the offered solutions were very specific to the package and project, and when applied did not fit my issue or resolve my problem. I suspect this has something to do with global.d.ts file but nothing looked out of place when I looked. If there are any suggestions on what is happening I will take them.
//Package.json
{
"name": "ts-node-server",
"version": "1.0.0",
"description": "project",
"main": "build/server.js",
"scripts": {
"compile": "tsc && node build/server.js",
"dev": "./node_modules/nodemon/bin/nodemon.js -e ts --exec \"npm run compile\""
},
"author": "..",
"license": "ISC",
"dependencies": {
"d3": "^6.6.2",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"p5": "^1.3.1",
"three": "^0.127.0"
},
"devDependencies": {
"#types/d3": "^6.3.0",
"#types/three": "^0.127.1",
"#types/express": "^4.17.11",
"#types/node": "^14.14.37",
"#types/p5": "^0.9.1",
"nodemon": "^2.0.7"
}
}
//tsconfig.json
{
"compilerOptions": {
"outDir": "./build",
"rootDir": "./src",
"module": "commonjs",
"moduleResolution": "node",
"noEmit": false,
"esModuleInterop": true,
"strict": true,
"target": "ES6"
},
"include": ["src/**/*"],
"exclude": ["**/node_modules", "**/config", "**/build", "**/*.md"]
}
If you must run p5.js functions in a Node.js application written in typescript, here's one way to do it:
Add npm dependencies: p5, window, canvas
Add npm devDependencies: #types/p5
Inject certain JSDOM window properties into the global scope: window, document, screen, navigator
Note: This works for the noise function, but I have no idea what the behavior of any functions that actually attempt to create or draw to a canvas would be.
Here's a working example in Repl.it.
Here's my package.json:
{
"name": "p5js-test",
"version": "1.0.0",
"description": "Test p5.js Node.js app.",
"scripts": {
"p5js-test": "ts-node --files src/main.ts",
"compile": "tsc"
},
"bin": {
"p5js-test": "./build/src/main.js"
},
"author": "Paul Wheeler",
"license": "MIT",
"dependencies": {
"canvas": "^2.7.0",
"p5": "^1.3.1",
"window": "^4.2.7"
},
"devDependencies": {
"#types/node": "^15.0.1",
"#types/p5": "^0.9.1",
"ts-node": "^9.1.1",
"typescript": "^4.2.4"
}
}
And here's my main.ts:
import Window from 'window';
// globals expected to exist by p5js (must come before the import)
// Note: doing this may not be entirely kosher according to the JSDOM documentation
// but it gets p5.js working
(<any> global).window = new Window();
(<any> global).document = global.window.document;
(<any> global).screen = global.window.screen;
(<any> global).navigator = global.window.navigator;
import p5 from 'p5';
const inst = new p5(p => {
// I'm not totally sure this is actually needed
p.setup = function() { };
});
console.log('using noise from instance: ' + inst.noise(1, 2, 3));

Include extra files inside app.asar using electron

It's a Vue app with electron-builder
{
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"electron:build": "vue-cli-service electron:build",
"electron:serve": "vue-cli-service electron:serve",
"postinstall": "electron-builder install-app-deps",
"postuninstall": "electron-builder install-app-deps",
},
"main": "background.js",
"dependencies": {
"core-js": "^3.6.5",
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^8.4.2",
"vue-router": "^3.3.2",
"vuetify": "^2.2.33"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.4.0",
"#vue/cli-plugin-eslint": "~4.4.0",
"#vue/cli-plugin-router": "~4.4.0",
"#vue/cli-plugin-typescript": "~4.4.0",
"#vue/cli-service": "~4.4.0",
"electron": "^6.1.12",
"typescript": "^3.9.5",
"vue-cli-plugin-electron-builder": "~1.4.6",
"vue-cli-plugin-vuetify": "~2.0.5",
"vue-template-compiler": "^2.6.11",
"vuetify-loader": "^1.3.0"
}
}
When I use npm run electron:build, this structure is generated:
And this is the content of app.asar:
background.js include all the dependencies. There are some external modules (from node_modules) that read files using something like fs.readFile(__dirpath + '/file'). As expected, these files are not included in the generated bundle, so I need to add them.
I've tried to use this in vue.config.js:
module.exports = {
lintOnSave: true,
transpileDependencies: [
'vuetify'
],
configureWebpack: {
devtool: 'source-map'
},
pluginOptions: {
electronBuilder: {
builderOptions: {
extraFiles: [
'node_modules/module/file'
]
}
}
}
}
But the file is included outside the app.asar, even with extraResources, and thus fs.readFile(__dirpath + '/file') did not find the file.
How can I include files inside app.asar?
The only way I found was using the public directory. Any file inside public/ will be copied to app.asar.
However, the file I need to copy belongs to an external lib, so to not make this file part of my project, I gitignored it and copy just before the build, using npm scripts.
"scripts": {
"build": "cp node_modules/lib/file public && vue-cli-service electron:build -wl",
"serve": "mkdir -p dist_electron && cp node_modules/lib/file dist_electron && vue-cli-service electron:serve"
}
I found out the path for files have to be relative path from dist_electron/bundled(or maybe other directory). So if we have directory named keys in root, the config should to be something like bellow.
module.exports = {
pluginOptions: {
electronBuilder: {
nodeIntegration: true,
builderOptions: {
files: [
"**/*",
{
from: "../../keys",
to: "./keys",
filter: ["**/*"],
},
],
},
},
},
};

SyntaxError: Unexpected token 'export' in Nodejs project with Typescript and Webpack

I have tried to find an answer to this solution but the answers I have found are usually to do with adding 'module' to a script tag (which doesnt apply in my case since I'm not writing browser code) or using import/export in a javascript file (which is not currently supported by Node) which means the need to use babel or typescript. Since I am seeing this error in a typescript project, I don't expect to see this error.
Actually, I have 2 typescript/webpack projects (with near identical setup, project A depends on project B) 1 importing definitions from the other.
In project B, I have several classes, 2 of which are exported, plus some other definitions. In project B's index.ts:
export * from './types';
export * from './specService/spec-option-service.class';
export * from './converter/xpath-converter.class';
and those are exported like so:
// types.ts
//
export interface IElementInfo {
readonly id?: string;
readonly recurse?: string;
readonly discards?: ReadonlyArray<string>;
readonly descendants?: {
readonly by?: string;
readonly throwIfCollision?: boolean;
readonly throwIfMissing?: boolean;
};
}
// ... plus other similarly defined exports
// specService/spec-option-service.class.ts
//
export class SpecOptionService { ...
// converter/xpath-converter.class.ts
//
export class XpathConverter { ...
And then in project B's index.ts, I export all the definitions (export * from blah) for use by the client as shown at the top of this post.
When I build project B, there is no such issues with the export.
After installing project B into project A
from a typescript file I am importing using:
import * as ProjectB from 'projectb';
Webpack successfully even builds project A's bundle, with no error. The error occurs at runtime, in this case when I go to run the tests at which point I see the following:
/Users/User/dev/github/js/projecta/node_modules/projectb/lib/index.ts:2
export * from './types';
^^^^^^
SyntaxError: Unexpected token 'export'
at Module._compile (internal/modules/cjs/loader.js:892:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.projectb (/Users/User/dev/github/js/projecta/dist/projecta-test-bundle.js:292:18)
At the end of projectb's webpack bundle, I found the following:
module.exports = webpack_require(/*! ./lib */"./lib/index.ts");
which I believe is at fault. Why does the bundle built by webpack for an "es5" target contain references to typescript? Isn't this bound to fail? I would have expected a require on the generated index.js file (not index.ts).
This is the first time I've done import/export across project boundaries in typescript so I know that I doing something wrong but what?
The tsconfig.json file in both projects are the same:
{
"compilerOptions": {
"allowJs": true,
"alwaysStrict": true,
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "Node",
"noImplicitAny": true,
"sourceMap": true,
"strictNullChecks": true,
"target": "es5",
"types": [
"mocha", "node"
],
"lib": [
"es5",
"es2015",
"es6",
"dom"
]
},
"include": [
"lib/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
And the webpack config:
{
devtool: 'source-map',
entry: {
index: './lib/index.ts'
},
target: 'node',
mode: mode,
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.ts(x?)$/,
use: 'ts-loader'
},
{
test: /\.json$/,
use: 'json-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }),
new webpack.BannerPlugin({
banner: '#!/usr/bin/env node',
raw: true
})
],
resolve: {
extensions: ['.ts', '.js', '.json']
},
watchOptions: {
ignored: /node_modules/
},
output: {
filename: 'projecta-bundle.js',
sourceMapFilename: 'projecta-bundle.js.map',
path: path.join(__dirname, 'dist'),
libraryTarget: 'commonjs'
}
}
Project A and B are plastikfan/jaxom and plastikfan/zenobia respectively. Before publishing the latest version of jaxom to npm, I am performing pre-npm-publish check (learnt that this is a wise thing to do with early npm packages) to check that clients can use the package as expected. (I've had problems in tha past where I've made a mistake in exporting something, but this does not become apparent until a client tries to use it. It's not somthing you can check for as far as I know before you publish. The advised way to to do this is to pack up your package using nom pack then install it into the client).
fyi, zenobia package.json is (cutdown version):
{
"name": "zenobia",
"version": "0.0.1",
"main": "lib/index.ts",
"scripts": {
"t": "mocha ./dist/zenobia-test-bundle.js",
"test": "npm audit --skip-unused && npm run t",
"build": "npm run build:d",
"build:d": "webpack -d --env.mode development",
"build:p": "webpack -p --env.mode production",
"build:t": "webpack --config webpack.config.test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/plastikfan/zenobia.git"
},
"dependencies": {
"#types/node": "^12.12.14",
"#types/ramda": "^0.26.36",
"jaxine": "^2.0.1",
"jaxom": "file:../NPM-LOCAL/jaxom-0.0.1.tgz",
"ramda": "^0.26.1",
"xmldom": "^0.1.27",
"xpath": "0.0.27"
},
"devDependencies": {
"#commitlint/cli": "^8.3.3",
"#commitlint/config-conventional": "^8.2.0",
"#types/chai": "^4.2.5",
"#types/dirty-chai": "^2.0.2",
"#types/mocha": "^5.2.7",
"#types/sinon": "^7.5.1",
"#types/sinon-chai": "^3.2.3",
"chai": "^4.2.0",
"commitizen": "^4.0.3",
"cz-conventional-changelog": "^3.0.2",
"depcheck": "^0.9.1",
"dirty-chai": "^2.0.1",
"mocha": "^6.2.2",
"nyc": "^14.1.1",
"precommit-hook": "^3.0.0",
"raw-loader": "^4.0.0",
"rimraf": "^3.0.0",
"semistandard": "^14.2.0",
"shebang-loader": "0.0.1",
"sinon": "^7.5.0",
"snazzy": "^8.0.0",
"ts-loader": "^6.2.1",
"tslint": "^5.20.1",
"tslint-config-semistandard": "^8.0.1",
"typescript": "^3.7.2",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-config-utils": "^2.3.1",
"webpack-node-externals": "^1.7.2"
}
}
And jaxom's cutdown package.json:
{
"name": "jaxom",
"main": "./lib/index.ts",
"scripts": {
"clean": "rimraf dist && rimraf decl",
"t": "mocha ./dist/jaxom-test-bundle.js",
"test": "npm audit --skip-unused && npm run t",
"build": "npm run build:d",
"build:d": "webpack -d --env.mode development",
"build:p": "webpack -p --env.mode production",
"build:t": "webpack --config webpack.config.test.js"
},
"dependencies": {
"#types/ramda": "^0.26.36",
"#types/xregexp": "^3.0.30",
"jinxed": "0.0.2",
"moment": "^2.24.0",
"ramda": "^0.26.1",
"xmldom-ts": "^0.3.1",
"xpath-ts": "^1.3.13",
"xregexp": "^4.2.4"
},
"devDependencies": {
"#commitlint/cli": "^8.2.0",
"#commitlint/config-conventional": "^8.2.0",
"#types/chai": "^4.2.5",
"#types/dirty-chai": "^2.0.2",
"#types/mocha": "^5.2.7",
"#types/sinon": "^7.5.1",
"#types/sinon-chai": "^3.2.3",
"chai": "^4.2.0",
"commitizen": "^4.0.3",
"cz-conventional-changelog": "^3.0.2",
"depcheck": "^0.9.1",
"dirty-chai": "^2.0.1",
"json-loader": "^0.5.7",
"mocha": "^6.2.2",
"precommit-hook": "^3.0.0",
"raw-loader": "^4.0.0",
"rimraf": "^3.0.0",
"sinon": "^7.5.0",
"sinon-chai": "^3.3.0",
"snazzy": "^8.0.0",
"ts-loader": "^6.2.1",
"tslint": "^5.20.1",
"tslint-config-semistandard": "^8.0.1",
"typescript": "^3.7.2",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-config-utils": "^2.3.1",
"webpack-node-externals": "^1.7.2"
}
}
For me, it was the module key in tsconfig.json.
I changed it from this:
"module": "esnext"
to this:
"module": "commonjs"
I think tsconfig can be a problem here.
Because when you are importing import * as ProjectB from 'projectb'; your projectB files will not be transpiled by typescript because of include and exclude properties of projectA tsconfig. Try add projectB to the compilation process of projectA.
Something like include: [ "lib/**/*", "my/path/to/projectB/**"] in projectA tsconfig.
Make sure you're running .js file not .ts.
Try adding "type":"module" to the package.json.

No metadata found for class-validator

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();

Categories

Resources