Error with Jest when trying to use `import` - javascript

I am using Jest to run tests on my JS code.
But currently, I am having an error:
Cannot use import statement outside a module
How can i fix this ?
I looked here but it does not what i am looking for: How to resolve "Cannot use import statement outside a module" in jest
This is my module:
class Path {
// code in here
}
export default Path;
This is the test file that exported from it:
import Path from "./Path";
// test() ...
This is my folder structure:

Related

Import javascript from node_modules in angular

I installed a npm package which contains a javascript file, what I want to use. The js file name is all.js and contains this code:
import { initExtended } from './extended'
import Header from './components/header/header'
function initAll(options) {
// Set the options to an empty object by default if no options are passed.
options = typeof options !== 'undefined' ? options : {}
// Allow the user to initialise GOV.UK Frontend in only certain sections of the page
// Defaults to the entire document if nothing is set.
var scope = typeof options.scope !== 'undefined' ? options.scope : document
// Find first header module to enhance.
var $toggleButton = scope.querySelector('[data-module="govuk-header"]')
new Header($toggleButton).init()
initExtended(options)
}
export {
initAll,
Header
}
File all.js is located in node_modules.
When I tried to import it directly from index.html like:
<script type="module" src="node_modules/#id-sk/frontend/govuk/all.js"></script>
It is not working. Console error, file not found.
I also tried import it via angular.json:
"scripts": [
"./node_modules/#id-sk/frontend/govuk/all.js"
]
Also not working with error "Uncaught SyntaxError: Cannot use import statement outside a module (at scripts.js:15241:1)". The error refers to line:
import { initExtended } from './extended'
I also tried to import it in polyfills but I don't know how to call it.
As you are speaking about angular.json, I assume that you are working in an Angular application bootstrapped using the Angular CLI with default settings.
To be able to use this package #id-sk/frontend in your typescript files, you have to import it directly into your typescript file.
1. Import #id-sk/frontend in your TS files
// Import everything into a local variable
import * as govuk from '#id-sk/frontend';
// Import specific object
import { HeaderExtended } from '#id-sk/frontend';
2. Run ng serve
⚠ Spoil: It will lead to typings errors
3. Let's add or create typings
As #id-sk/frontend is not written in typescript, the compile doesn't know about the typings of this library.
Following this statement, you have two choices:
Find or contribute to DefinitelyTyped in order to create the typings of your package #id-sk/frontend
Create a local file typings.d.ts in your ./src folder to declare an empty module
declare module "#id-sk/frontend"
4. Kill & run ng serve again
Enjoy it!
Go further
You can add typings to your module in order to give you autocompletion on the provided objects of #id-sk/frontend.
``ts
declare module "#id-sk/frontend" {
export interface Options {
scope?: Document
}
export function initAll(options: Options): void;
}

Can't import Vonage Client SDK into my preact (vite) project

I have a Preact project using Vite. I want to use the nexmo-client SDK from vonage but when I import using the ES method it breaks my project.
// app.tsx
import NexmoClient from 'nexmo-client';
I get the following error in the console.
index.js:19 Uncaught ReferenceError: global is not defined
at index.js:19:19
at index.js:12:22
at node_modules/nexmo-client/dist/index.js (index.js:16:1)
at __require (chunk-J43GMYXM.js?v=f3505250:11:50)
at dep:nexmo-client:1:16
However if I import it using via a script tag it works just fine.
// index.html
<script src="node_modules/nexmo-client/dist/nexmoClient.js"></script>
// app.tsx
const NexmoClient = window.NexmoClient;
OK, there are two problems here.
Firstly, NexmoClient tries to use global which is not available on the browser.
Secondly, NexmoClient has a dependency on socket.io-client, for some reason Vite imports a Node version of the socket.io-client that again tries to use modules that are not available on the browser, namely 'child_process'.
To fix both issues you can provide the following config to Vite, this should make sure the resulting build is compatible with the brother.
// vite.config.js or vite.config.ts
import { defineConfig } from 'vite'
import preact from '#preact/preset-vite'
export default defineConfig({
plugins: [preact()],
define: {
global: {},
},
resolve: {
alias: {
"xmlhttprequest-ssl": "./node_modules/engine.io-client/lib/xmlhttprequest.js"
}
}
})

Cypress not recognizing my imported module from outside /cypress directory

I am trying to import a module from a file outside my /cypress directory into the /cypress/integration directory's test.spec.js file like so:
import { LAB_MODEL } from '../../models/search/lab-model';
But inside this imported module "LAB_MODEL" there are other files being imported using the "##" at the start of the file imports like
import ExperimentDetails from "##/components/experiment/ExperimentDetails";
and I think this is why Cypress isn't working and giving me this error:
Error: Webpack Compilation Error
./models/search/lab-model.js
Module not found: Error: Can't resolve '##/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'
resolve '##/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'
Parsed request is a module
using description file: /Users/hidden/package.json (relative path: ./models/search)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
So I think this is the reason why my test won't run, but I have no idea how to make Cypress recognize "##" imports and can't find any documentation/stackoverflow answers, any help is appreciated, thanks!
##/ looks like something that gets translated into a full path during the Nuxt build.
(ref The alias Property).
Cypress has a separate build that doesn't know about this Nuxt feature. You could try to replicate it with some webpack config via a preprocessor, but another way is to have your Nuxt app put a reference to lab_model on the window object
// somewhere in the Nuxt app
if (window.Cypress) {
window.lab_model = LAB_MODEL;
}
then at the top of the test
const lab_model = cy.state('window').lab_model;
This has the benefit of giving you the exact same instance of lab_model, in case you wanted to stub something.
In a starter Nuxt app, I added the code window.lab_model = LAB_MODEL in /pages/index.vue, but you can add it in any component that imports it, right after the import statement.
In the spec add a .should() to test the property exists, to allow the app time to settle.
it('gets labModel from the Nuxt app', () => {
cy.visit('http://localhost:3000/')
cy.window()
.should('have.property', 'lab_model') // retries until property appears
.then(labModel => {
console.log(labModel)
// test with labModel here
})
})

Can't import vue2-google-maps component to main.js

After installing vue2-google-maps with npm, I'm trying to import the component to my main.js. But I keep getting an error. I never had problem importing packages to main.js or to other .vue files.
Versions:
vue 2.6.10
vue2-google-maps#0.10.7
vue-cli 2.9.6 but also tried with 3.11.0
import App from "./App.vue";
import store from "./store/store.js";
import * as VueGoogleMaps from "vue2-google-maps";
Vue.use(
VueGoogleMaps,
{
load: {
key: "AIzaSyBYULuuIqKYMJVrEk1PjpUDQQYkGMmP0iM",
libraries: 'places'
}
}
);
I'm getting the error in this line : import * as VueGoogleMaps from "vue2-google-maps";
Error Message: Could not find a declaration file for module 'vue2-google-maps'.
'c:/Users/BotiVegh/vueJS_projects/vue-store-gallery-map/node_modules/vue2-google-maps/dist/main.js'
implicitly has an 'any' type. Try npm install
#types/vue2-google-maps if it exists or add a new declaration (.d.ts)
file containing declare module 'vue2-google-maps';ts(7016)
Do I need to change something in the config file?
You could try adding "noImplicitAny": false to your tsconfig.json file
This disables warnings on expressions and declarations with an implied 'any' type

Gulp throwing "is read-only while parsing file" error while running Gulp task

I'm trying to create ES6 module in JavaScript and I get error like: Line 20: "NotFound" is read-only while parsing file.
The NotFound is the name of my module.
'use strict';
import React from 'react';
const NotFound = React.createClass({
render: function () {
return (
<h1>Not Found!</h1>
);
}
});
export default NotFound;
I'm importing it the following way: import NotFound from './components/NotFound';
How to solve this issue? Changing file rights to 777 doesn't help at all (I know it's incorrect, but I was trying to find a solution).
Ok, it looks like I had defined a variable before calling import. The variable name was exactly the same as the imported module name. That was the root of the issue.

Categories