I'm new to React, still struggling to understand some basics, sorry if my question seems to be weird. We know we need to import modules as
import sth from 'sth';
so when we use Jest, don't we need to do as:
import { test, expect...} from 'Jest';
As #nahanil points out, Jest puts the methods you need in the global scope of your NodeJS runtime. If you put a console.log(global) in your file when running jest, you will see the methods are hooked onto the global scope. Other libraries such as assert does not follow the same convention, and you will need to import the assertions you need.
That happens here:
https://github.com/facebook/jest/blob/160d27ae9b6728dccf268f8a98351bcf82a7d9e1/packages/jest-environment-node/src/index.ts#L21
As explained in the first section in official documentation api
📚 :
In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them. However, if you prefer explicit imports, you can do import {describe, expect, test} from '#jest/globals'.
import {describe, expect, test} from '#jest/globals'
Related
When we write code in index.js file in src folder of an React app first of all we write this line:
import React from 'react';
I know react is a package
But I want to know what is React basically
an object, a method or something else.
The React variable that you import is an object, and it contains most of the methods that are used by React when generating a web-page.
The reason this import has been historically required is because the JSX that you write (e.g. return <p>text</p>) gets converted into a function call, calling the React.createElement function.
Note that in newer versions of React you no longer need to import react when using JSX. See https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html for more information.
Credit to Olivier Boissé for an answer in the comments.
In order to find out what React is, you just need to write:
console.log(react);
Then you will see that it is an object with many properties and methods.
String:
import React from "react";
We are writing in order to import this object into a file where we will use some of its method. If you don't use anything from React in the file, then you don't need to import it.
For example, in react 18, it is no longer necessary to import the react object into a file index.js
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
In any case, at this stage of your study of react, it may not be entirely clear to you what is used in it and for what, but in the future you will become more aware of all the possibilities of react. There is a time for everything
I am trying to test my React (for the browser) code in what I think is an entirely conventional way: Mocha as the test-runner, JSDom to simulate the browser, Enzyme to check the results.
My problem is this: whenever I manually set the focus on a component, React throws an exception. The problem is deep inside React:
activeElement.attachEvent('onpropertychange', handlePropertyChange);
The active element is set, but as a JSDom HTMLInputElement, it does not have an attachEvent. I have found if I hacked the file node_modules/jsdom/lib/jsdom/living/generated/HTMLInputElement.js to give that class empty methods named attachEvent and detachEvent, the exception goes away.
But clearly, that is not the right solution.
The comments on the function, and some fragmentary information I have found elsewhere, suggests this is a shim meant for antique versions of IE, not JSDom at all. The function involved, startWatchingForValueChange is only invoked if the flag isInputEventSupported is not set, and setting it requires another canUseDOM to be set. Forcibly setting either of those flags causes other problems.
Typing up this question, I figured it out.
As the testing system was set up, when I initialized JSDom, I also set a global afterEach() to reset the contents of the DOM after each test. This did not directly create a problem, but it did mean the order of initialization was necessarily like this:
React
Mocha
JSDom
So when React was initialized, it looked around and saw no working DOM, and figured, "Damn, I must be running on IE or something." After that, it was all down-hill.
So I confidently restructured it like this:
JSDom
React
Mocha
And that... did nothing.
Then I realized the problem was, I was doing this:
import { JSDOM } from "jsdom";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
global.jsdom = initDom();
...
React was actually initializing itself when it was imported — by the import of Enzyme!
So I confidently rewrote it like this:
import { JSDOM } from "jsdom";
global.jsdom = initDom();
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
And that... did nothing.
Because the import statement effectively gets hoisted to the top of the file.
So I confidently rewrote it like this:
import { JSDOM } from "jsdom";
let jsdom = new JSDOM("");
...
const Enzyme = require("enzyme");
const Adapter = require("enzyme-adapter-react-16");
And that... fixed it.
I have a setting style file like:
GlobalStyles.js
export const GlobalStyles={
ViewContainer:{flex:1, justifyContent:'center', alignItems:'center'},
Center:{justifyContent:'center', alignItems:'center'},
FontNormal:15,
FontMedium:18,
FontLarge:28,
FontHeader:38
}
module.export={GlobalStyles}
and when i used it in another JS file, let say Home.js. i want to vscode know every Key:Value i've defined,
with those export in GlobalStyles.js vscode suggesting an import style like this:
import { GlobalStyles } from '../Component/GlobalStyles';
and my expected result is something like:
import { ViewContainer, Center, FontMedium, [and so on]} from '../Component/GlobalStyles';
how to let vscode suggesting me Auto Import foo from path/to/GlobalStyles when i'm typing foo? where foo is like ViewContainer, Center, FontMedium, [and so on].
The feature you're talking about is called Auto Imports. To answer your question, this feature exists and works by default in VSCode.
Here is a sample of how i've used it in a React project. Here I have a component inside a folder with the same name. Outside of that folder is a file I called ModuleExports.js and it currently has the following code.
import Navbar from "./Navbar/Navbar";
export { Navbar };
For reference, export is an alias of module.export so feel free to use them interchangeably. This is a component so when I try to use it as such you can see from the screenshot I am suggested an import to use.
The same can be done without being a component. I'll declare a testObject inside the same file ModuleExports.js and export it.
Then let's see if intellisense will pick it up.
There it is. I hope this helps and do ask if you want more clarification or are running into issues.
In this case, the mistake seems to be using dynamic export. That's old CommonJs style. VSCode uses typescript tools for static analysis. To take advantage of that, you have to use ES6 export.
CommonJs: module.export={GlobalStyles}
ES6-modules: export GlobalStyles
The significant difference between two is that CommonJs variant is simply variable which is defined at runtime. Ie. there is no way to know what you are exporting without executing the code. ES6 export is reserved word. It's construct which cant be changed after definition which also means, it's type definition can be found without actually executing the code.
Typescript, Babel etc provide interoperability between two module systems but they are two very different things by spec.
In my file sketch.js before shifting to combined p5 and react, I had a command
amp = new p5.Amplitude();
after shifting to react, the 'p5' method is not defined anymore.
p.Amplitude()/song.Amplitude() isn't doing the job and returns
(TypeError: ... .Amplitude is not a constructor)
I really don't know from where or how import p5. I guess its something to do with the web config but not sure what.
I've npm install both p5 and react-p5-wrapper, and except this line and rest of the things that required amp all the code running as expected, and I can play music/adjust background with sliders etc ...
at the begging of the file I'm importing:
import React from 'react';
import 'p5/lib/addons/p5.sound';
import 'p5/lib/addons/p5.dom';
I will really be glad for little help!
You might be able to try:
import * as p5 from './{library-path}/p5.js';
It looks like P5 was not originally set up for easy ES6 imports.
This GitHub issue from 2016 seems to identify a similar problem. https://github.com/processing/p5.js/issues/1734
More recently it looks like it can be used correctly with NPM:
https://medium.com/front-end-weekly/learning-the-p5-canvas-drawing-library-in-es6-and-webpack-bf514a679544
Also check out this other potential answer here.
How to use React with p5.js
I present you the following code:
https://plnkr.co/edit/xxNW1xAIPoGtTK84OxGq
NOTE: This does not work because of SystemJS which I just can not configure. Whoever wants can edit if freely to make it work. I have been using the angular-cli and default webpack config and this works.
My question is about the "AlertService" which is needed to display an "alert". It has been extracted in the core module. However when I need to use it I have import it like so import { AlertService } from '../core/alert/alert.service' as present in dashboard.component.ts in order to inject it.
Doesn't this break the modular approach since I have to give it the path to the class ? If I change the location of the AlertService within the CoreModule I still have to go and change the string in the DashboardComponent. Also in this example if AlertService is not present DashboardComponent will not fire ... but DashboardComponent is part of the DashboardModule which should be able to start on its own - otherwise what is the point of the modules if they are coupled statically I could just put everything in one place.
What I want is to create a general alert component which I only need to include and once in the whole app and be able to use it everywhere.
But I think I am misunderstanding the concept of modules and/or how to use them. I have read the Modules' section in Angular.io multiple times and gone through multiple tutorials.
Best regards
If having to change lots of file paths bothers you a lot, one possible solution is to add another layer - create a services.ts file, then have the canonical imports there rather than in each component. That way, you only have to update one file if you change the path:
services.ts:
import { AlertService } from './alert.service';
// ES2015 shorthand property initializer
export default {
AlertService
};
yourComponent.ts:
import { AlertService } from "../services";
...
If you want a component to work even if a service is not present, you can make it an optional dependency (returning null if it doesn't exist), but TypeScript forces you to still have to import the service into the file to get code completion/typings. That's always felt a little janky to me.