Jest not recognising JQuery Object ($) - javascript

I have used JavaScript to created a simple web application to measure how much time I spend on different projects.
I want to test the code with Jest and this works fine until I try to test a function that contains the JQuery object ($).
This is the error message I get:
ReferenceError: $ is not defined
The answers I have found online tells me that I need to add a jQuery dependency in my global object, which I have done. Below is my package.json file:
"jest": {
"setupFiles": ["PathToSetupFile/setup-jest.js"],
"type": "module"
and my setup-jest.js:
import $ from 'jquery';
global.$ = global.jQuery = $;
I am now met with a new error message:
SyntaxError: Cannot use import statement outside a module
I cannot find any further information on how to fix this. A few resources tell me I need to update my jest.config.js file but this file does not exist anywhere in my node modules.

I thought it would be helpful to start completely from the beginning and therefore address a much wider scope but never the less provide the exact answer to your problem at the end of my response here.
In PowerShell CD to your project folder
Install the jest node modules locally into your project folder using
npm install --save-dev jest
Install jest globally so you can use it as a CLI command
npm install jest -g
This installs Jest globally i.e. to your user profile %APPDATA%\npm location
Ensure %APPDATA%\npm is in your user profile environment PATH variable (in Windows settings, "Edit Environment variables for your account")
Check in your PowerShell console that it is in your path using $Env:PATH. (If your %APPDATA%\npm path still isn't showing then restart the PowerShell window, if the terminal is inside VSCode then you will have to restart VSCode so that the terminal inherits the new environment)
In order to import jquery you will need to a) install jquery and b) define a setup file for jest which is referenced in jest.config.js created using jest --init in your project folder.
Install jquery -
npm install --save-dev jquery
Generate jest.config.js -
jest --init
The following questions will help Jest to create a suitable configuration for your project
√ Would you like to use Typescript for the configuration file? ... no
√ Choose the test environment that will be used for testing » jsdom (browser-like)
√ Do you want Jest to add coverage reports? ... yes
√ Which provider should be used to instrument code for coverage? » v8
√ Automatically clear mock calls, instances, contexts and results before every test? ... yes
✏️ Modified your\project\folder\package.json
📝 Configuration file created at jest.config.js
If you don't specify the jsdom (browser-like) test environment then running code under test that uses jquery will yield an error of "jQuery requires a window with a document"
But this means the 'jest-environment-jsdom' must now be installed
(As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.) -
npm install --save-dev jest-environment-jsdom
Edit jest.config.js
Change
// setupFiles: [],
To
setupFiles: [ './jest.setup.js' ],
N.B. the "./" prefix is required otherwise jest will state it cannot find the jest.setup.js file.
The create jest.setup.js in your project folder and add the following -
const $ = require('jquery');
global.$ = global.jQuery = $;
Node uses the CommonJS module system (https://nodejs.org/en/knowledge/getting-started/what-is-require/)
so the above syntax is required to work with Node.js

Related

test function is not recognized as a global function

I followed a JavaScript unit testing tutorial at acadamind.com in that tutorial instructor used Vitest for demonstrations and the reason they mentioned using Vitest instead of Jest was Jest needed some extra configuration to work with the latest JavaScript syntax.
After doing my own research about unit testing I realized industry demand unit testing skills with the Jest. So I followed another tutorial for learning unit testing with Jest and React Testing Library (RTL).
I created a brand new TypeScript project with Create React App (CRA) and followed the instructions in that tutorial and everything went well. The instructor mentioned that Jest and RTL are supported out of the box with CRA.
After studying unit testing I tried to apply that knowledge and write some tests with my application, which was created some time back, and recently we updated it to React Scripts 5. In that application, I check node_modules folder, and Jest is there as a dependency. But I have noticed that the following packages are not listed in the package.json file in my project, so I installed them:
#testing-library/jest-dom": "^5.16.5",
#testing-library/react": "^13.4.0",
#testing-library/user-event": "^14.4.3",
#types/jest": "^29.4.0",
After that, I noticed my new project has this file in the src folder so I have copy pasted this file as well.
setupTest.ts
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '#testing-library/jest-dom';
When I tried to run when I tried to write my first unit test I noticed that VS Code doesn't recognize this test function as a global function and indicates an error and then I try to run the test script and I am getting this error
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/home/pathum/Documents/tagd/node_modules/axios/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import axios from 'axios';
| ^
2 | // config
3 | import { HOST_API } from '../config';
4 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/utils/axios.ts:1:1)
at Object.<anonymous> (src/hooks/useRefresh.tsx:2:1)
at Object.<anonymous> (src/hooks/useAxiosPrivate.tsx:3:1)
at Object.<anonymous> (src/pages/contracts/contract-form/new-contact-person.tsx:12:1)
at Object.<anonymous> (src/pages/contracts/contract-form/parties.tsx:15:1)
at Object.<anonymous> (src/pages/contracts/contract-form/contract-form.tsx:9:1)
at Object.<anonymous> (src/pages/contracts/contract-form/contract-form.test.tsx:2:1)
at TestScheduler.scheduleTests (node_modules/#jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/#jest/core/build/runJest.js:404:19)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.398 s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.
Seems I need to do some configurations for Jest to work properly in the application. How do I fix this?
Install the necessary dependencies: npm install --save-dev #babel/preset-typescript and npm install --save-dev jest-cli typescript
Create a new file in the root of your project called jest.config.js and add the following content to it:
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
};
Add a new property called "jest" to the "scripts" section of your package.json file and set it to the following: "jest --config jest.config.js --coverage". This will tell Jest to use the configuration file you just created and also generate a coverage report.
Create a new file in the root of your project called tsconfig.test.json and add the following content to it:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./test-dist"
},
"include": [
"src/**/*.test.ts"
]
}
Finally, you can run your tests with npm run jest.
You also need to make sure that you are using import statement correctly in your tests. You should use import statement to import functions, classes, and variables from other modules, but you should use require statement to import modules that are not written in TypeScript.

Angular testing - test.ts not found

I'm trying to follow the official Angular docs to set up testing for an Angular project - https://angular.io/guide/testing#service-tests
I've downloaded the sample Angular project from the page above, using the first (top) link. I've done an npm install and when I run ng serve it builds fine.
When I run ng test using the CLI, I get the message:
ERROR in Entry module not found: Error: Cant' resolve 'C:Code\testing\src\test.ts' in 'C:\Code\testing'
ERROR in error TS6053: File 'C:Code\testing\src\test.ts' not found.
I looked at this question - How to resolve test.ts when running ng test?, but in that case the file actually exists, but in the Angular example project it doesn't exist at all.
(When I first ran ng test I originally got a message about Jasmine Marbles being missing, which I resolved using:)
npm install jasmine-marbles --save
The documentation says:
You can fine-tune many options by editing the karma.conf.js and the
test.ts files in the src/ folder.
So I know the test.cs is some kind of configuration file, but how do I generate it? It doesn't exist in the Angular 'live example' project either. And how do I know that a test.cs I generate will work reliably with this project?
I used #joshbaeha's suggestion to ng new a new Angular 5 project and copied the test.ts file, which appears to be completely generic and not reliant on project structure or anything else. Everything is now working. Here it is:
test.ts
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '#angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '#angular/platform-browser-dynamic/testing';
declare const require: any;
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
I don't know whether you can generate just the test.ts file or not, but as far as i know this file is automatically generated when you create a new angular project using angular-cli. So you can just create a new project using angular-cli then copy the src/test.ts file from that new project

Unable to compile and publish my Typescript library using webpack or TSC

Ive created a library that helps to trace an object state using rx streams and
Im trying to publish it to npm community.
you can check this out In my github repo
I want to compile my library to a single Javascript file and also create a declaration file ".d.ts" for Typescript users.
As i understand, when running $ npm publish i release my entire repository. what i want is to release the dist folder with the library source and declaration file and so the end users will be able to debug my library if necessary through their code so i need also source map.
So first i need to compile my src directory to a single javascript file and i have 2 ways to do so, using tsc or with webpack.
What ive tried so far and you should know:
I used module alias, configured in tsconfig.json.
I separated the library's bussiness logic to multiple files.
I wanted to import internal library's modules using "#lib" prefix.
so in my tsconfig.json i added:
"paths": {
"#lib/*": [
"src/*"
]
},
That alone cause some problems.
first of all running the command:
$ tsc src/index.ts
doesn't work at all and it shows me an error:
src/index.ts(3,15): error TS2307: Cannot find module '#lib/state-traceable'.
src/index.ts(4,15): error TS2307: Cannot find module '#lib/traceable-decorator'. src/index.ts(5,15): error TS2307: Cannot find module '#lib/effect-decorator'.
src/index.ts(6,15): error TS2307: Cannot find module '#lib/meta'.
yet running the command:
$ tsc
does actually works but it compiles each source file and create declaration file for each one of them.
Additionally, it preserves the path alias "#lib/*" instead of compiling it to something javscript compatible with relative paths "../", "./" etc...
Using webpack:
I succeed to bundle all my library sources to a single file and get rid of the "#lib" prefix however im not able to create a single declaration file.
im using "awesome-typescript-loader" plugin for webpack.
I created an issue, thought its a bug but i yet received any response from them:
https://github.com/s-panferov/awesome-typescript-loader/issues/559
Also tried to get some help from Gitter chats, Typescript community, "awesome-typescript-loader" library has no dedicated chat but couldn't find any useful information. Most of the examples ive seen, Typescript library publishers used to create a single file in their source directory: "index.ts" and it makes life easier because you can use tsc and compile that single file to a javascript file.
I hope i will find salvation here.
Some general info about the environment itself:
OS: Windows 10 Pro
Node Version: 9.5.0
npm version: 5.6.0
webpack version: 4.2.0
Please use the path configuration like below
"paths": {
"#lib/state-traceable": ["src/state-traceable.ts"],
"#lib/meta": ["src/meta.ts"],
"#lib/effect-decorator": ["src/effect-decorator.ts"],
"#lib/traceable-decorator": ["src/traceable-decorator.ts"],
"#lib/contracts/*": ["src/contracts/*"],
"#lib/utils/*": ["src/utils/*"],
"#lib/rx-operators/*": ["src/rx-operators/*"]
},

bundle a large node.js application into a single .js file

I would like to bundle a largish node.js cli application into a single .js file.
My code is structured as follows:
|- main.js
|--/lib
|----| <bunch of js files>
|--/util
|----| <bunch of js files>
...etc
I can use browserify to bundle the whole thing into one file using main.js as the entry point, but Browserify assumes the runtime environment is a browser and substitutes its own libraries (e.g. browserify-http for http). So I'm looking for a browserify-for-node command
I tried running
$ browserify -r ./main.js:start --no-builtins --no-browser-field > myapp.js
$ echo "require('start') >> myapp.js
but I'm getting a bunch of errors when I try to run $ node myapp.js.
The idea is that the entire application with all dependencies except the core node dependencies is now in a single source file and can be run using
$ node myapp.js
Update
=============
JMM's answer below works but only on my machine. The bundling still does not capture all dependencies, so when I try to run the file on another machine, I get dependency errors like
ubuntu#ip-172-31-42-188:~$ node myapp.js
fs.js:502
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT, no such file or directory '/Users/ruchir/dev/xo/client/node_modules/request/node_modules/form-data/node_modules/mime/types/mime.types'
You can use pkg by Zeit and follow the below steps to do so:
npm i pkg -g
Then in your NodeJS project, in package JSON include the following:
"pkg": {
"scripts": "build/**/*.js",
"assets": "views/**/*"
}
"main": "server.js"
Inside main parameter write the name of the file to be used as the entry point for the package.
After that run the below command in the terminal of the NodeJS project
pkg server.js --target=node12-linux-x64
Or you can remove target parameter from above to build the package for Windows, Linux and Mac.
After the package has been generated you have to give permissions to write:
chmod 777 ./server-linux
And then you can run it in your terminal by
./server-linux
This method will give you can executable file instead of a single .js file
Check out the --node option, and the other more granular options it incorporates.

How to require jQuery.loadTemplate using browserify

I have setup browserify with Gulp.
When I require jQuery, everything works:
var $ = require('jquery');
When I try to require jquery load template module
var loadTemplate = require('jquery.loadtemplate')
I get an error
module "jquery.loadtemplate " not found
I installed loadtemplate using npm like this
npm install --save jquery.loadtemplate
I think there is an error in the package.json of the jquery.loadtemplate module. It should define the source of the plugin somewhere and it's missing. In other modules the source is defined in the "main" property. It should say something like
"main": "jquery-loadTemplate/jquery.loadTemplate-1.5.0.js",
depending on the location of the script file. You can change it manually, but then it'll be deleted the next time you update/reinstall your npm package.

Categories

Resources