Jest cannot find module sometimes - javascript

actually i'm trying to test a function and getting that error:
Files that i'm using:
searchUserService
import { SearchUserService } from '../../src/service/searchUser.service';
import { SearchUserRepository} from '../../src/repository/searchUser.repository'
import { Util } from 'src/util/util'
let userId = '123456'
describe('', () => {
it('', async () =>{
const res = new SearchUserService(new SearchUserRepository(new Util)).searchCredential(userId)
expect(res).toBe('')
})
})
package.json
{
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nodemon",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "tslint -p tsconfig.json -c tslint.json",
"test": "node_modules/.bin/jest --config jest.conf.js --detectOpenHandles",
"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.7.2",
"#nestjs/core": "6.7.2",
"#nestjs/platform-express": "6.7.2",
"axios": "0.19.2",
"lodash": "4.17.15",
"reflect-metadata": "0.1.13",
"rimraf": "3.0.0",
"rpc-proxy": "^1.0.7",
"rxjs": "6.5.3",
"swagger-ui-express": "4.1.3",
"typescript": "3.6.3"
},
"devDependencies": {
"#nestjs/cli": "6.9.0",
"#nestjs/schematics": "6.7.0",
"#nestjs/swagger": "4.2.7",
"#nestjs/testing": "6.7.1",
"#types/express": "4.17.1",
"#types/jest": "24.0.18",
"#types/node": "12.7.5",
"#types/supertest": "2.0.8",
"dotenv": "8.2.0",
"jest": "24.9.0",
"nodemon": "2.0.2",
"prettier": "1.18.2",
"supertest": "^4.0.2",
"ts-jest": "24.1.0",
"ts-node": "8.4.1",
"tsconfig-paths": "3.9.0",
"tslint": "5.20.0",
"yamljs": "0.3.0"
}
}
searchUser.service.ts
import { Injectable } from '#nestjs/common';
import { BaseService } from '********************';
import { SearchUserRepository } from '../repository/searchUser.repository';
#Injectable()
export class SearchUserService extends BaseService {
constructor(private readonly searchUserRepository: SearchUserRepository) {
super();
}
async searchCredential(userId: string) {
this.logger.info(`[SearchUserService] - searchCredential - userId = ${userId}`, '');
return await this.searchUserRepository.searchCredential(userId);
}
}
jest.conf.js
const path = require('path');
module.exports = {
rootDir: path.resolve(__dirname, './'),
verbose: true,
preset: 'ts-jest',
testEnvironment: 'node',
collectCoverage: true,
coverageDirectory: process.env.JEST_CLOVER_OUTPUT_DIR || './_devops/coverage',
coverageReporters: ['text', 'clover', 'lcov'],
collectCoverageFrom: [
'**/src/**/*.{ts}',
'!**/spec/**/*.{ts}',
'!**/tests/**/*.{ts}',
],
moduleFileExtensions: [
'ts',
'tsx',
'js',
'json',
'jsx'
]
};
I've tried with another functions and debug, when i start the debug, the error instantly happens doesn't give any chance, with another functions I get the same.
it appears to be an Import error from Jest or NestJs.
I've checked the documentation of Jest and some Issues that appears to be same as i'm getting, but non of them resolved my problem.

Related

This problem occurred when I used jest in vue cil

file: user.service.js
import axios from "axios";
class UserService {
static getAll() {
return axios.get("/user-all");
}
static getById(id) {
return axios.get(`/user/${id}`);
}
}
export default UserService;
file: userApi.spec.js
import UserService from "#/api/user.service.js";
import axios from "axios";
describe("用户模块", () => {
it("获取所有用户数据", async () => {
});
});
the code is error, when i run npm run test:unit.
the error is import axios from './lib/axios.js'.
I think the point is import.
error
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
i guess the problem is axios in node_modules.
It seems that babel doesn't work.
so what should I do?
even if the jest.config.js is configured like this
jest.config.js
module.exports = {
preset: "#vue/cli-plugin-unit-jest",
transformIgnorePatterns: ["node_modules/(?!(axios)/)"],
};
babel.config.js
module.exports = {
presets: [
"#vue/cli-plugin-babel/preset",
],
};
package.json
{
"name": "01",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"test:unit": "vue-cli-service test:unit",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^3.8.3",
"vue": "^3.2.13"
},
"devDependencies": {
"#babel/core": "^7.12.16",
"#babel/eslint-parser": "^7.12.16",
"#vue/cli-plugin-babel": "~5.0.0",
"#vue/cli-plugin-eslint": "~5.0.0",
"#vue/cli-plugin-unit-jest": "~5.0.0",
"#vue/cli-service": "~5.0.0",
"#vue/test-utils": "^2.0.0-0",
"#vue/vue3-jest": "^27.0.0-alpha.1",
"babel-jest": "^27.0.6",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-vue": "^8.0.3",
"jest": "^27.0.5",
"prettier": "^2.4.1"
}
}
code:https://github.com/xiaohun254700/problem-warehouse

Configure imports relative to root directory in create-react-library library

I am trying to setup a react component library with create-react-library (which uses rollup under the hood) and port over our application's existing component library so that we can share it between applications. I am able to create the library, publish to a private git registry, and consume it in other applications. The issue is that I have had to change all of my imports to relative imports which is rather annoying as I am planning on porting over a large amount of components, hocs and utils.
The entry point of the package is the src dir. Say I have a component in src/components/Text.js and a hoc in src/hoc/auth.js. If I want to import withAuthentication from src/hoc/auth.js into my Text component, I have to import it like import { withAuthentication } from "../hoc/auth" but I'd like to be able to import with the same paths I have in my existing application so it's easy to port over components, like import { withAuthentication } from "hoc/auth"
I have tried a lot of config options, jsconfig.json the same as my create-react-app application, manually building my library with rollup rather then using create-react-library so I'd have more config options but to no avail.
Below are the relevant bits from my package.json as well as my jsconfig.json, any help would be greatly appreciated, I am sure I am not the only person who's had this issue.
Here's the package.json
{
"main": "dist/index.js",
"module": "dist/index.modern.js",
"source": "src/index.js",
"files": [
"dist"
],
"engines": {
"node": ">=10"
},
"scripts": {
"build": "microbundle-crl --no-compress --format modern,cjs",
"start": "microbundle-crl watch --no-compress --format modern,cjs",
"prepare": "run-s build",
"test": "run-s test:unit test:lint test:build",
"test:build": "run-s build",
"test:lint": "eslint .",
"test:unit": "cross-env CI=1 react-scripts test --env=jsdom",
"test:watch": "react-scripts test --env=jsdom",
"predeploy": "cd example && npm install && npm run build",
"deploy": "gh-pages -d example/build"
},
"peerDependencies": {
"react": "^16.0.0",
"react-html-parser": "^2.0.2",
"lodash": "^4.17.19",
"#material-ui/core": "^4.11.0",
"react-redux": "^7.1.1",
"redux": "^4.0.1",
"redux-localstorage": "^0.4.1",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"react-router-dom": "^5.1.1",
"react-dom": "^16.13.1",
"react-scripts": "^3.4.1",
"react-svg": "^12.0.0",
"reselect": "^4.0.0"
},
"devDependencies": {
"microbundle-crl": "^0.13.10",
"babel-eslint": "^10.0.3",
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.7.0",
"eslint-config-standard": "^14.1.0",
"eslint-config-standard-react": "^9.2.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.17.0",
"eslint-plugin-standard": "^4.0.1",
"gh-pages": "^2.2.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.0.4"
},
"dependencies": {
"node-sass": "^7.0.0"
}
}
and here's the jsconfig:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
The example from the following link maybe you should navigate to your src file from the BaseUrl, or if you "src" is in the same directory as your config it should be only "."
https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping
Example from link above:
{
"compilerOptions": {
"baseUrl": ".", // This must be specified if "paths" is.
"paths": {
"jquery": ["node_modules/jquery/dist/jquery"] // This mapping is relative to "baseUrl"
}
}
}
You need to do 3 things
tsconfig.json this enables typescript autocomplete
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"src/*": ["./src/*"],
"src": ["./src"]
}
}
}
babel.config.js this plugin resolves relative modules
module.exports = {
plugins: [
[
'module-resolver',
{
alias: {
src: './src'
}
}
]
]
}
package.json // install babel-plugin-module-resolver
{
//...
"devDependencies": {
//...
"babel-plugin-module-resolver": "^3.2.0",
// ...
}
}

getting rid of relative path react (removing "../..")

I have downloaded a react project with the following package.json :
{
"private": true,
"main": "src/index.js",
"dependencies": {
"#material-ui/core": "4.10.0",
"#material-ui/icons": "4.9.1",
"classnames": "2.2.6",
"history": "4.10.1",
"moment": "2.26.0",
"node-sass": "4.14.1",
"nouislider": "14.5.0",
"prop-types": "15.7.2",
"react": "16.13.1",
"react-datetime": "2.16.3",
"react-dom": "16.13.1",
"react-router-dom": "5.2.0",
"react-scripts": "3.4.1",
"react-slick": "0.26.1",
"react-swipeable-views": "0.13.9"
},
"devDependencies": {
"#babel/cli": "7.10.1",
"#babel/plugin-proposal-class-properties": "7.10.1",
"#babel/preset-env": "7.10.1",
"#babel/preset-react": "7.10.1",
"eslint-config-prettier": "6.11.0",
"eslint-plugin-prettier": "3.1.3",
"eslint-plugin-react": "7.20.0",
"gulp": "4.0.2",
"gulp-append-prepend": "1.0.8",
"prettier": "2.0.5"
},
"optionalDependencies": {
"typescript": "3.9.3"
},
"scripts": {
"start": "NODE_PATH=src/ react-scripts start",
"build": "react-scripts build && gulp licenses",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"lint:check": "eslint . --ext=js,jsx; exit 0",
"lint:fix": "eslint . --ext=js,jsx --fix; exit 0",
"install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && npm install && npm start",
"build-package-css": "node-sass src/assets/scss/material-kit-react.scss dist/material-kit-react.css",
"build-package": "npm run build-package-css && babel src --out-dir dist",
"compile-sass": "node-sass src/assets/scss/material-kit-react.scss src/assets/css/material-kit-react.css",
"minify-sass": "node-sass src/assets/scss/material-kit-react.scss src/assets/css/material-kit-react.min.css --output-style compressed",
"map-sass": "node-sass src/assets/scss/material-kit-react.scss src/assets/css/material-kit-react.css --source-map true"
}
}
I dont know how the developer got rid of relative path in his code.
for example he imports modules like:import Header from "components/Header/Header.js";
although if I try to the same , i should do it like:import header from "../../../src/components/Header/header.js".
the link to the original github:
https://github.com/creativetimofficial/material-kit-react/
i have downloaded and installed this one , it works fine.
but when i try to copy some of the codes,it doesnt work.
use the jsconfig.json to set absolute path instead of reletive , as described in documentation
in the provided project he used
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"*": ["src/*"]
}
}
}
so he could accees all files using a absolute path , in all folder and subfolders of the project like
import file from "component/file/file.js"
In the root directory of your project, create a jsconfig.json file and save this;
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"],
"exclude": ["node_modules"]
}
If you are using eslint in your project, you'll need to add this in your .eslintrc.js file;
...
settings: {
'import/resolver': {
node: {
paths: ['src'],
},
},
},
...
You should be able to import files by their absolute path now.

License conflicts in nuxt

I'm facing an issue when I build my nuxt app.
When I run 'npm run build', it says:
WARNING in The comment file "LICENSES" conflicts with an existing asset, this may lead to code corruption, please use a different name.
Here's my package.json file:
{
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate",
"lint": "eslint --ext .js,.vue --ignore-path .gitignore ."
},
"dependencies": {
"#nuxtjs/axios": "^5.3.6",
"babel-runtime": "^6.26.0",
"marked": "^0.8.2",
"node-sass": "^4.13.1",
"nuxt": "^2.0.0",
"sass-loader": "^8.0.2",
"vue-fragment": "^1.5.1",
"vue-pdf": "^4.0.7",
"vue-slick-carousel": "^1.0.2",
"vue-youtube": "^1.4.0",
"vuelidate": "^0.7.5"
},
"devDependencies": {
"#nuxtjs/eslint-config": "^1.0.1",
"#nuxtjs/eslint-module": "^1.0.0",
"#nuxtjs/vuetify": "^1.10.2",
"babel-eslint": "^10.0.1",
"eslint": "^6.1.0",
"eslint-config-prettier": "^4.1.0",
"eslint-plugin-nuxt": ">=0.4.2",
"eslint-plugin-prettier": "^3.0.1",
"license-webpack-plugin": "^2.1.4",
"prettier": "^1.16.4"
}
}
Here's the console output:
How can I know which packages conflict with license files?
For me the culprit was the terser webpack plugin. Disabling the terser.extractComments option in build config under nuxt.config.js got rid of the warnings.
nuxt.config.js
export default {
// ... other nuxt config,
build: {
// ... other build config,
terser: {
extractComments: false // default was LICENSES
}
}
}

nyc coverage reports empty with babel mocha

I am using mocha to unit test my js code which is using babel also. I am using nyc to do coverage. But in the end, the result is showing empty.
Why does it show All files 0 even though my test file is requiring redux.js and number-reducer.js files ?
my test script inside package.json is
{
...
"scripts": {
...
"test": "cross-env NODE_ENV=test npm run lint && nyc --reporter=lcov --reporter=text mocha",
"coverage": "nyc report --reporter=text-lcov | coveralls"
},
...
"devDependencies": {
"#babel/core": "~7.3.4",
"#babel/preset-env": "~7.3.4",
"#babel/register": "~7.0.0",
"babel-loader": "~8.0.5",
"babel-plugin-istanbul": "~5.1.1",
"babel-polyfill": "~6.26.0",
"chai": "~4.2.0",
...
"cross-env": "~5.2.0",
"eslint": "~5.15.0",
"mocha": "~6.0.0",
"nyc": "~13.3.0",
...
"webpack": "~4.29.4",
"webpack-cli": "~3.2.1"
},
"nyc": {
"require": [
"#babel/register"
],
"reporter": [
"lcov",
"text"
],
"sourceMap": false,
"instrument": false
}
}
My .babelrc file is
{
"presets": [
"#babel/preset-env"
],
"env": {
"test": {
"plugins": ["istanbul"]
}
}
}
My test.spec.js file is
import chai from "chai";
let redux = require("../src/js/redux").redux;
let NumberReducer = require("../src/js/number-reducer").NumberReducer;
const expect = chai.expect;
describe("ReduxModule", function () {
it('should expect an object', function () {
const ReduxModule = redux(NumberReducer);
expect(ReduxModule).to.be.a("object");
});
describe('ReduxModule#getState', function () {
it('should give me zero', function () {
const ReduxModule = redux(NumberReducer);
expect(ReduxModule.getState()).to.equal(0);
});
...
});
});

Categories