This problem occurred when I used jest in vue cil - javascript

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

Related

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",
// ...
}
}

.env file loading without dotenv package

This is my first time dealing with typescript and I have no idea of what is happening. When I start my application with the command yarn dev:server the app loads the environment variables defined on the .env file, although i removed the dotenv package.
// package.json
{
"name": "server",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev:server": "ts-node-dev --respawn --transpile-only src/index.ts",
"typeorm": "npx ts=node ./nodemodules/typeorm/cli.js",
"test": "NODE_ENV=test jest"
},
"devDependencies": {
"#types/cors": "^2.8.10",
"#types/express": "^4.17.11",
"#types/jest": "^26.0.23",
"#types/node": "^14.14.41",
"#typescript-eslint/eslint-plugin": "^4.22.0",
"#typescript-eslint/parser": "^4.22.0",
"eslint": "^7.25.0",
"eslint-config-node": "^4.1.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^3.4.0",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"supertest": "^6.1.3",
"ts-node-dev": "^1.1.6",
"typescript": "^4.2.4"
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"pg": "^8.6.0",
"reflect-metadata": "^0.1.13",
"typeorm": "^0.2.32"
}
}
// app.js
import "reflect-metadata";
import express, { Application } from "express";
import cors from "cors";
import "./database/connect";
import custumerRoutes from "./app/routes/Custumer";
interface IAppController {
express: Application;
}
class AppController implements IAppController {
express: Application;
constructor() {
this.express = express();
this.middlewares();
this.routes();
}
middlewares() {
this.express.use(cors());
this.express.use(express.json());
}
routes() {
this.express.use("/custumer", custumerRoutes);
this.express.get("/", (req, res) => {
res.send("🔥 server up and running");
});
}
}
const app = new AppController().express;
export { app };
is it possible that one of the packages i'm using is automatically loading the environment variables? if so, would it be possible to disable this functionality?
I found out that dotenv is a dependency of the package typeorm. This is why it was loading automatically.

Jest cannot find module sometimes

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.

Vue.use(plugin) not invoking the `install` function

I am working on exporting my custom vue component as NPM module. I have followed steps mentioned in the official doc Packaging Vue Components for npm.
My index.js AKA wrapper.js file:
// index.js -> wrapper.js
// Import vue component
import component from "./components/VueOpenapiForm.vue";
import ExtendSchema from "./functional-components/extend-schema.js";
// global components
import ObjectForm from "./components/ObjectForm.vue";
import ArrayInput from "./components/ArrayInput.vue";
import KeyValuePairs from "./components/KeyValuePairs.vue";
import SimpleInput from "./components/SimpleInput.vue";
// export ExtendSchema
export const extendSchema = ExtendSchema;
// Declare install function executed by Vue.use()
export function install(Vue) {
if (install.installed) return;
install.installed = true;
Vue.component("VueOpenapiForm", component);
Vue.component("object-form", ObjectForm);
Vue.component("array-input", ArrayInput);
Vue.component("key-value-pairs", KeyValuePairs);
Vue.component("simple-input", SimpleInput);
}
// Create module definition for Vue.use()
const plugin = {
install
};
// Auto-install when vue is found (eg. in browser via <script> tag)
let GlobalVue = null;
if (typeof window !== "undefined") {
GlobalVue = window.Vue;
} else if (typeof global !== "undefined") {
GlobalVue = global.Vue;
}
if (GlobalVue) {
GlobalVue.use(plugin);
}
// To allow use as module (npm/webpack/etc.) export component
export default component;
rollup.config.js file:
// rollup.config.js
import babel from "rollup-plugin-babel";
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs"; // Convert CommonJS modules to ES6
import vue from "rollup-plugin-vue"; // Handle .vue SFC files
import buble from "#rollup/plugin-buble"; // Transpile/polyfill with reasonable browser support
export default {
input: "src/index.js", // Path relative to package.json
output: {
name: "VueOpenapiForm",
exports: "named"
},
plugins: [
resolve(),
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
"vue-codemirror": ["codemirror"]
}
}),
babel({
runtimeHelpers: true,
exclude: "node_modules/**",
plugins: [
"#babel/plugin-external-helpers",
"#babel/plugin-transform-runtime"
]
}),
vue({
css: true, // Dynamically inject css as a <style> tag
compileTemplate: true // Explicitly convert template to render function,
}),
buble() // Transpile to ES5
]
};
package.json
{
"name": "#appscode/vue-openapi-form",
"version": "0.1.0",
"main": "dist/vue-openapi-form.umd.js",
"module": "dist/vue-openapi-form.esm.js",
"unpkg": "dist/vue-openapi-form.min.js",
"browser": {
"./sfc": "src/vue-openapi-form.vue"
},
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"pkg": "npm run pkg:umd & npm run pkg:es & npm run pkg:unpkg",
"pkg:umd": "rollup --config pkg/rollup.config.js --format umd --file dist/vue-openapi-form.umd.js",
"pkg:es": "rollup --config pkg/rollup.config.js --format es --file dist/vue-openapi-form.es.js",
"pkg:unpkg": "rollup --config pkg/rollup.config.js --format iife --file dist/vue-openapi-form.min.js"
},
"dependencies": {
"#babel/runtime": "^7.7.7",
"bulma": "^0.8.0",
"bulma-switch": "^2.0.0",
"core-js": "^3.3.2",
"font-awesome": "^4.7.0",
"vee-validate": "^3.1.3",
"vue": "^2.6.10",
"vue-codemirror": "^4.0.6",
"vuex": "^3.0.1"
},
"devDependencies": {
"#babel/plugin-external-helpers": "^7.7.4",
"#babel/plugin-transform-runtime": "^7.7.6",
"#rollup/plugin-buble": "^0.20.0",
"#rollup/plugin-node-resolve": "^6.0.0",
"#vue/cli-plugin-babel": "^4.0.0",
"#vue/cli-plugin-eslint": "^4.0.0",
"#vue/cli-service": "^4.0.0",
"#vue/eslint-config-prettier": "^5.0.0",
"babel-cli": "^6.26.0",
"babel-eslint": "^10.0.3",
"eslint": "^5.16.0",
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-vue": "^5.0.0",
"node-sass": "^4.12.0",
"prettier": "^1.18.2",
"rollup": "^1.17.0",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.0.1",
"rollup-plugin-uglify-es": "0.0.1",
"rollup-plugin-vue": "^5.0.1",
"sass-loader": "^8.0.0",
"vue-template-compiler": "^2.6.10"
},
"description": "A Vue component to generate html form using OpenAPI v3 schema",
"repository": {
"type": "git",
"url": "git+https://github.com/appscode/vue-openapi-form.git"
},
"keywords": [
"json-schema",
"vue",
"openapi",
"kubernetes"
],
"author": "support#appscode.com",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/appscode/vue-openapi-form/issues"
},
"homepage": "https://github.com/appscode/vue-openapi-form#readme"
}
When I run npm run pkg rollup bundles the component and produces 3 files in the dist folder.
vue-openapi-form.es.js
vue-openapi-form.min.js
vue-openapi-form.umd.js
Now, I am trying import this bundled component inside a different Vue project. In the new project in main.js file:
// main.js
...
import VueOpenapiForm from "#appscode/vue-openapi-form"
Vue.use(VueOpenapiForm)
...
Now, when I try to use vue-openapi-form as html tag inside vue template. I have the following error
[Vue warn]: Unknown custom element: <vue-openapi-form> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
found in
---> <App> at src/App.vue
Can anyone tell me what am I doing wrong here ?
I need all those components to be declared globally as they are recursive. The install function does just that but it is not being called when I use Vue.use. How can I solve this ?

`Vue is not defined` error

I created a vue project via vue cli 3. To structure my code, I made a dir called common where I keep files with .js ext. So, I transferred some code from my .vue file which was in views folder and surprisingly it did not work.
I imported Vue like import Vue from 'vue'; and set a debugger. When I hover over the Vue, it says undefined. I even imported my custom js file to check and same issue there too.
package.json
{
"name": "demo-app",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test:unit": "vue-cli-service test:unit"
},
"dependencies": {
"axios": "^0.18.0",
"vue": "^2.5.17",
"vue-axios": "^2.1.3",
"vue-cookie": "^1.1.4",
"vue-router": "^3.0.1",
"vuex": "^3.0.1"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^3.0.0-rc.12",
"#vue/cli-plugin-eslint": "^3.0.0-rc.12",
"#vue/cli-plugin-unit-mocha": "^3.0.0-rc.12",
"#vue/cli-service": "^3.0.0-rc.12",
"#vue/eslint-config-airbnb": "^3.0.0",
"#vue/test-utils": "^1.0.0-beta.20",
"chai": "^4.1.2",
"vue-template-compiler": "^2.5.17"
}
}
common/apiService.js
import Vue from 'vue';
import { API_URL } from '#/common/config';
import axios from 'axios';
const ApiService = {
init() {
debugger
axios.defaults.baseURL = API_URL;
},
get(resource, slug = '') {
return axios
.get(`${resource}/${slug}`)
.catch((error) => {
throw new Error(`[PTE] ApiService ${error}`);
});
},
post(resource, params) {
debugger
return axios.post(`${resource}`, params);
},
};
export default ApiService;
please note that i have imported Vue but have not used it. Will use it later after i fix this issue.

Categories